zoukankan      html  css  js  c++  java
  • 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')
    );
  • 相关阅读:
    BZOJ5321 JXOI2017加法(二分答案+贪心+堆+树状数组)
    BZOJ5089 最大连续子段和(分块)
    Codeforces 893F(主席树+dfs序)
    BZOJ5092 分割序列(贪心)
    Codeforces Round #525 Div. 2 自闭记
    364. Nested List Weight Sum II
    362. Design Hit Counter
    369. Plus One Linked List
    370. Range Addition
    366. Find Leaves of Binary Tree
  • 原文地址:https://www.cnblogs.com/laojun/p/6112003.html
Copyright © 2011-2022 走看看