Featured image of post React 16 之实例那些事

React 16 之实例那些事

React16 学习第一篇,分享自己总结的学习笔记以及需要注意的点。.

React16 学习第一篇,分享自己总结的学习笔记以及需要注意的点。

开发环境搭建

1
npm i -g create-react-app

如果网络不好,推荐使用淘宝镜像 cnpm 安装。

1
create-react-app demo1

React 实例

删除 src 下文件,从零开始写。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import React,{Component, Fragment} from 'react'
class List extends Component{
  render(){
    return (
      <Fragment>
        <input />
        <button>Add</button>
        <ul>
          <li>1.Create</li>
          <li>2.Modify</li>
          <li>3.Upload</li>
        </ul>
      </Fragment>
    )
  }
}

export default List

<Fragment>可以让组件返回一系列元素,不用添加额外的 Dom 节点。

事件绑定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import React,{Component, Fragment} from 'react'
class List extends Component{
  constructor(props){
    super(props)
    this.state = {
      inputValue: 'default',
      list: ['Sing','Dance','Basketball']
    }
  }
  render(){
    return (
      <Fragment>
        {/* 绑定 this */}
        {/* 绑定事件需要用驼峰命名法 */}
        <input value={this.state.inputValue} onChange={this.inputChange.bind(this)} />
        <button onClick={this.addContent.bind(this)}>Add</button>
        <ul>
          {
            this.state.list.map((item,index)=>{
              // 绑定 this 和 index
              return <li key={item+index} onClick={this.deleteItem.bind(this,index)}>{item}</li>
            })
          }
        </ul>
      </Fragment>
    )
  }
  
  inputChange(e){
    this.setState({
      inputValue: e.target.value
    })
  }

  addContent(){
    this.setState({
      list: [...this.state.list, this.state.inputValue],
      inputValue: ''
    })
  }

  // 删除列表项
  deleteItem(index){
    // console.log(index)
    // 不能直接操作 state 里的值 需要赋值给一个局部变量 再操作
    let list = this.state.list
    list.splice(index,1)
    this.setState({
      list: list
    })
  }
}

export default List
Built with Hugo
Theme Stack designed by Jimmy