在学习React的Hadding Events这一章节,发现事件回调函数的几种写法,看似区别不大,但实际差异还是蛮大的。
class Toggle extends React.Component{ constructor(props) { super(props); this.state = {isToggleOn:false}; //necessary this.bindClick = this.bindClick.bind(this);//推荐写法 }; bindClick(){ this.setState( prevState => ({ isToggleOn : !prevState.isToggleOn }) ) }; render() { return ( // <button onClick={(e) => this.bindClick(e)}> //这种写法导致每次呈现组件都要创建一个回调方法,浪费性能 <button onClick={this.bindClick}> {this.state.isToggleOn ? "ON" : "OFF"} </button> ) }; } ReactDOM.render(<Toggle /> ,document.getElementById("example"))
通常使用推荐写法
2、列表中的key
在React中,列表中的key很关键,虽然不是必需的,但是
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity
并且如果封装一个列表组件,key最好赋给封装组件,而非原始列表,
key不会作为组件的props传递
如下:key赋给ListItem而非li
function ListItem(props) { const value = props.value; return ( // Wrong! There is no need to specify the key here: <li key={value.toString()}> {value} </li> ); } function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => // Wrong! The key should have been specified here: <ListItem value={number} /> ); return ( <ul> {listItems} </ul> ); } const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('root') );