一、类组件的 两种创建方式
1. ES5方式
import React form 'react'
const A = React.createClass({render(){<div>hi</div>}})
export default A
由于ES5不支持class 所以使用这种方式
2.ES6方式
import React form 'react'
class B extends React.Component{
constructor(props){
super(props)
// ...
}
render(){
return(<div>hi</div>)
}
}
export default B
二、Props
1.初始化
class B extends React.Component{
constructor(props){ super(props)
// super(props)后,props会出现在this上,this.props就是外部数据对象的地址了
// ...
}
render(){
//...
}
}
2.读取
class B extends React.Component{
constructor(props){ super(props)
// super(props)后,props会出现在this上,this.props就是外部数据对象的地址了
// ...
}
render(){
<div onClick={this.props.add}>
{this.props.name}
</div>
}
}
通过this.props.xxx 来读取
3.写入
不准写,永远不准尝试对props进行改写
4.Props 的作用
(1)用来接收外部数据
外部数据只能读不能写,由父组件进行传递
(2)接收外部函数
在恰当时机调用该函数,由父组件进行提供
三、State
1.初始化
class B extends React.Component{
constructor(props){
super(props)
this.state = {
n:1,
m:2
}
}
render(){
//...
}
}
2.读取
在组件内部写 this.state.n
3.写入
调用this.setState(参数1,参数2),参数2为一个函数,这个函数会在回调成功后调用。
注意:setState 是一个异步的操作,不会立即改变this.state。setState会自动合并state里面第一层的数据
四、绑定事件
// 可用
<button onclick={()=>this.addN()}> n+1 </button>
<button onclick={this.addN.bind(this)}> n+1 </button>// 不可用<button onclick={this.addN}> n+1 </button>// 这种写法会使得里面的this变成window,因为没有传this// 当用于点击button的时候 react 运行的是 button.onClick.call(),这时的call并没有传入参数,所以这时候this === null,这时候addN的this为undefind ,为nudefind 就会变成window// 推荐写法 使用箭头函数addN =()=> this.setState()