在學習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') );