React之事件綁定、列表中key的使用


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM