React conditional rendering and recycling

Conditions rendering

React in the same conditions rendering and JavaScript, use JavaScript or operator if the conditional operator to create an element to represent the current state, then let React to update the UI according to them.
The following specific implementation examples can be seen
1. src -> components folder, then the new list.js , specific code as follows:

import React, { Component } from 'react';
class List extends Component {
    //  状态的初始化一般放在构造器中
    constructor(props){
        super(props);

        this.state = {
            goods: [
                {id: 1,text: '条件渲染'},
                {id: 2,text: '循环渲染'}
            ],
        }
    }
    render() {
        return (
            <div>
                {/* 条件渲染 */}
                { this.props.title && <h1>{this.props.title}</h1> } {/* 短路逻辑 */}

                {/* 列表渲染 */}
                <ul>
                    {this.state.goods.map( good  => <li key={good.id}>{good.text}</li> )}
                </ul>
            </div>
        );
    }
}

export default List;

2. Then src -> index.js import component, reuse, specific code as follows:

import React from 'react';
import List from './component/List'

function App() {
  return (
    <div>
      {/* 条件渲染与循环 */}
      <List title="条件渲染与循环Demo"></List>
    </div>
  );
}
export default App;

Guess you like

Origin www.cnblogs.com/-muzi/p/11964806.html