首页 > 代码库 > react学习笔记3

react学习笔记3

      <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