標籤:關鍵字 val round cat put 學習 item 資料 通過
<div id="demo"></div> <script type="text/babel"> var ItemComponent = React.createClass({ render:function (){ return ( <li>{this.props.item}</li> ) } }); var ListComponent = React.createClass({ render:function (){ return ( <ul> { this.props.listArr.map(function (item,index){ return <ItemComponent key={index} item={item} /> }) } </ul> ) } }); var FirstComponent = React.createClass({ mixins:[React.addons.LinkedStateMixin], getInitialState:function (){ return { mes:this.props.value, listArr:this.props.listArr } }, render:function (){ return ( <div> <h1>{this.props.title}</h1> <input type="text" ref="text_input" valueLink={this.linkState("mes")} />/*引入react-with-addons庫,並配置mixins:[React.addons.LinkedStateMixin]後,可以使用linkState,類似雙向資料繫結,其實本質是內部實現了onChange事件*/ /*ref屬性可以使當前元素通過this.refs.text_input找到*/ <input type="button" onClick={this.addItemHandle} value={this.props.sendName} /> /*this指向問題,沒搞懂*/ <p>{this.state.mes}</p> <ListComponent listArr = {this.state.listArr}/>
/*這裡用this.state.listArr,而不用this.props.listArr,是因為state可變,要向子組件傳遞改變後的值*/ </div> ) }, addItemHandle:function (){ var value = this.refs.text_input.value; var newArr = this.state.listArr.concat([value]) this.setState({listArr:newArr}) } }); var obj = { title:‘react‘, sendName:‘提交‘, value:"請輸入留言", listArr:[1,2,3,4,5,6,7,8] } ReactDOM.render( <FirstComponent {...obj} />, document.getElementById("demo"), function(){ console.log("頁面渲染完成"); } );/*JSX裡面不要寫分號,會報錯*//*class是關鍵字,要寫成className*//*設定樣式時,要寫成sytle={xx:xxx}的形式*/ </script>
react學習筆記3