react条件渲染&列表&key

条件渲染

条件渲染比较简单,阅读官网相关文档即可.

列表

通过map渲染列表:

class HelloWorld extends React.Component {
  constructor(props){
    super(props);
    this.state = ({
      arr: [1,2,3,4]
    })
  }  
  render(){
    return (
      <ul>
        {
          this.state.arr.map(item=>(
            <li>li_{item}</li>
          ))
        }  
      </ul>
    )
  }
}
// 通过调用React自身方法render可以得到当前组件的实例对象,并渲染到页面容器.
ReactDOM.render(<HelloWorld />,document.getElementById('root'));

key

我们发现报错, Each child in a list should have a unique "key" prop. 意思是我们每一个遍历的元素都应该有一个唯一的key,这个和vue是一样的,用于react在底层渲染的时候区分组件. 原则上我们不能使用数组的下标作为key,因为数组增删会影响下标,而应该给数据提供唯一的值.
这里我们确定arr的每一项是唯一的,我们可以采用值作为key. 实际开发中建议使用数组元素对象的id作为key.

class HelloWorld extends React.Component {
  constructor(props){
    super(props);
    this.state = ({
      arr: [1,2,3,4]
    })
  }  
  render(){
    return (
      <ul>
        {
          this.state.arr.map(item=>(
            <li key={item}>li_{item}</li>
          ))
        }  
      </ul>
    )
  }
}
// 通过调用React自身方法render可以得到当前组件的实例对象,并渲染到页面容器.
ReactDOM.render(<HelloWorld />,document.getElementById('root'));

猜你喜欢

转载自blog.csdn.net/m0_67388537/article/details/131954719
今日推荐