7. 使用...展开,合并数组。 - yiqunkeke/react-jianshu-shangguigu-zty GitHub Wiki

import React, { Component, Fragment } from "react";

class TodoList extends Component {
    constructor(props) {
        super(props)
        this.state = {
            inputValue: 'hello',
            list: ['学英语', '学React']
        }
    }
  render() {
    return (
      <Fragment>
        <div>
          <input value={this.state.inputValue} onChange={ (e) => this.handleInputChange(e) }/>
          <button onClick={ this.handleBtnClick }>提交</button>
        </div>
        <ul>
            {
              this.state.list.map((item, index) => {
                return (
                  <li key={index}>{item}</li>
                )
              })  
            }
        </ul>
      </Fragment>
    );
  }

  handleInputChange = (e) => {
    this.setState({
      inputValue: e.target.value
    })
  }

  handleBtnClick = () => {
    // 使用...展开一个数组
    this.setState({
      list: [...this.state.list, this.state.inputValue],
      inputValue: ''
    })
  }
}

export default TodoList;

总结:

使用 ...展开一个数组,再使用[ , ]拼接数组
⚠️ **GitHub.com Fallback** ⚠️