react 条件渲染、列表渲染

1.class组件
  class Cc extends React.Component {
    state = {
      show: true,
      arr: [{ name: '121' }, { name: "2323" }, { name: '432435' }]
    }
    handleShow() {
      this.setState({
        show: !this.state.show
      })
    }
    showFc() {
      return this.state.show ? '显示' : '隐藏'
    }
    addArr() {
      let arr = [...this.state.arr]
      arr.push({ name: '新的name' })
      this.setState({
        arr: arr
      })
    }
    render() {
      return <div>
        <Button type="primary">class组件</Button>
        <br></br>
        <Button type="primary" onClick={this.handleShow.bind(this)}>{this.showFc()}</Button>
        <div>列表渲染</div>
        {
          this.state.arr.map((item, index) => {
            return <div key={index}>姓名:{item.name}</div>
          })
        }
        <Button type="primary" onClick={this.addArr.bind(this)} size="small">添加数据</Button>
      </div>
    }
  }

 

2.函数组件
let [show, setShow] = useState(true)
  function fixShow() {
    setShow(!show)
  }
  let [arr, setArr] = useState([{ name: '121' }, { name: "2323" }, { name: '432435' }])
  function addArr() {
    let newArr = [...arr]
    newArr.push({ name: '新的name' })
    setArr(newArr)
  }
  return <div className={styles.container}>
    <div>条件渲染和列表渲染</div>
    <Button type="primary">函数组件</Button>
    <br></br>
    <Button type="primary" onClick={fixShow}>{show ? '显示' : '隐藏'}</Button>
    <div>列表渲染</div>
    {show ?
      arr.map((item, index) => {
        return <div key={index}>姓名:{item.name}</div>
      })
      : ''}
    <Button type="primary" onClick={addArr} size="small">添加数据</Button>
    <Cc></Cc>
  </div>
    ;

  

posted on 2021-03-29 14:20  sss大辉  阅读(78)  评论(0编辑  收藏  举报

导航