React loops through rendering array objects

Let’s make the most basic case, the bottom navigation bar

We define the array in seat

 state = {
        list: [
            { id: 1, text: '首页' },
            { id: 2, text: '分类' },
            { id: 3, text: '我的' },
        ],
        nav: 1
    }

The loop rendering of react is different from that of vue. In vue, we all use the encapsulated methods, while react uses the native js map method to achieve loop rendering of data. This is what others often say, if there is no need, don’t add instances to React.

// 内容
<div className='body'>
    {this.which()}
</div>
// 底部导航栏
<div className='nav_header'>
     {this.state.list.map((item, index) =>
         <div key={index}
              className={this.state.nav == item.id ? 'active' : ''}
              onClick={() => {
                  // 通过点击事件去给 this.state.nav 重新赋值
                  this.state.nav = item.id
                  this.setState({
                     // 更改底部导航选中状态
                     nav: this.state.nav
                   })
               }}>
              <span className='btn'>{item.text}</span>
          </div>
      )}
</div>

The key value here also represents a unique identifier.

this.setState method

We all know that there is a two-way data binding effect in Vue, and the data update view will also be updated accordingly. But react doesn't, so here we need to change the data through this.setState method, let the component's render re-render, and refresh the data.

What we want to achieve is that clicking on the content in the navigation will also switch accordingly. We call the which method here to determine the displayed component content

which() {
     switch (this.state.nav) {
         case 1:
               return <Home></Home>
         case 2:
               return <Classify></Classify>
         case 3:
               return <User></User>
         default:
               return null
     }
}

Guess you like

Origin blog.csdn.net/m0_61672533/article/details/128559218