1.this的作用域
deleteProgram: function(){ alert("delete"); }, render: function(){ return( <ul> { this.state.programs.map(function(bill,index) { return <li> <button onClick={this.deleteProgram} value={index}>Delete</button> //注意这个是用的that </li>; }) } </ul> ); }
上述代码,点击之后是没有反应的,因为this.deleteProgram中的this指代的function,但是function内没有这个函数,故没有反应。此时需要
deleteProgram: function(){ alert("delete"); }, render: function(){ var that = this; //保存this的作用域 return( <ul> { this.state.programs.map(function(bill,index) { return <li> <ChannelProgram start_time={bill["start_time"]} end_time={bill["end_time"]} title={bill["program"]["name"]}/> <button onClick={that.deleteProgram} value={index}>Delete</button> //注意这个是用的that </li>; }) } </ul> ); }
当然使用es6的语法,即可避免这个坑onClick={ (e) => this.deleteProgram(e) }
2.React复合组件更新
组件内部要添加componentWillReceiveProps这个函数,它是组件收到新的props时会触发(即当父级组件render刷新了子组件的props时触发),此时更新状态,即可,
否则,父组件的值刷新了,子组件的值不会更新的
父组件的代码
render: function(){ var that = this; return( <ul> { this.state.programs.map(function(bill,index) { return <li><ChannelProgram change={that.props.change} start_time={bill["start_time"]} end_time={bill["end_time"]} title={bill["program"]["name"]}/></li>; }) } </ul> ); }
子组件的
var ChannelProgram = React.createClass({ getInitialState: function() { return { start_time: this.props.start_time, end_time: this.props.end_time, title: this.props.title } }, componentWillReceiveProps: function(nextProps,nextState) { this.setState({ start_time: nextProps.start_time, end_time: nextProps.end_time, title: nextProps.title }); }, render: function(){ var start_time = this.state.start_time; var end_time = this.state.end_time; var title = this.state.title; return( <div> <input id="start_time" value={start_time} onChange={this.props.change}/> <input id="end_time" value={end_time} onChange={this.props.change}/> <input id="title" value={title} onChange={this.props.change}/> </div> ); } });
3.key值的使用
React是根据组件上设定的key属性来生成该组件唯一的标识,只有key改变了,React才会更新组件,否则重用该组件。如果想要更新组件内容,请保证每次的key都不一样。
render: function(){ var that = this; return( <ul> { this.state.programs.map(function(program,index) { return <li key={new Date().getTime()+index} className="channel-program"> <ChannelProgram program_index={index} day={that.props.day} change={that.props.change} bill={program}/> </li>; }) } </ul> ); }