Class组件的两种创建方式ES5的Class创建方式
impor React from 'react'
const A =React.createClass({
render(){
return(
)
}
})
export default A
是ES5的创建方式,由于ES5不支持Class关键字,所以需要创建Class组件的 时候需要先引入React。
然后声明一个变量,它等于React.createClass如上面代码↑,然后它接受一个选项 通过render一个函数将div返回,最后将这个变量A导出。ES6的Class创建方式
impor React from 'react'
class B extends React Component{
constructor(props){
super(props)
}
render(){
return(
)
}
}
export default B;
在ES6的语法当中,class继承了React Component,constructor可以理解为初始化,然后render。
Props 外部数据
props的作用在于接受外部数据,只能读不能写,外部数据是由父组件传递。接受外部函数,在恰当的时机调用该函数,同样该函数一般是父组件的的函数。
传入Props给B组件
class Parent extend React Component{
constructor(props){
super(props)
this.state.name = {name:'shisan'}
}
onClick = ()=>{}
render(){
return
onClick = {this.onClick}>hi
}
}
在这里我们有一个Parent的组件,然后里面有一个state.name = {name:'shisan'} 。
然后return一个B组件,把this.state.name 作为B的外部数据,吧onClick函数传给onClick属性。
B组件里面的“name”和“onClick”就是props。
外部数据被封装成了一个对象{name:'shisan',onClick:...,children:'hi'} ,onClick是一个回调。
Props 初始化
class B extends React.Component{
constructor(props){
super(props)
}
render(){}
}
初始化就是constructor里面的,props就是接收外面传进来的数据,然后调用super(props),props会挂载到this上面。这样做了之后,this.props就是外部数据对象的地址了。
prosp 外部数据
class B extends React conponent{
constructor(props)
super(props)
}
render{
return
{this.props.name}
}
B的render里面把外部传进来的函数付给div,可以直接将会name展示出来。
children就是我们刚开始传的hi,可以将其展示在页面上面。
State读取内部数据 & setState写入内部数据
初始化State
class B extends React.componnent{
constructor(props){
super(props)
this.state = {
user:{name:'shisan',age:'18'}
}
}
render(){/*...*/}
}
上面代码在constructor里面初始化了State,name:'shisan',age:'18' 。
读写 State读用this.state
this.state.xxx.yyy.zzz写用this.setState(???,fn)
setState接受两个参数,第二个就是fn
第一种参数:this,setState(newState,fn)
注意!setState不会立刻改变this。state会在当前代码运行完之后,再去更新this.state,从而触发UI更新
第二种参数:this.setState((state.props)=>newStaet,fn)
fn 会在写入成功后执行写时候会 shallow merge
setState会自动将新的state与旧的state进行一级合并。