1.react数据流以及组件间沟通
react是自上而下的单向数据流,从父节点传递到子节点(通过props);如果顶层的props改变,react会重新渲染所有子节点。
props:用于组件间状态的传递,用于整个组件树中传递数据和配置,在当前组件访问props使用this.props;
state 指的是组件内部的状态,只能从当前组件调用this.setState修改state值,一般更新子组件都是通过改变state值,更新新子组件的props值而得到更新。
组件沟通
- 父子组件沟通
- 父组件传递数据给子组件
通过传递props即可实现。
- 父组件传递数据给子组件
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {
msg: 'haha'
}
}
componentDidMount(){
setTimeout(() => {
this.setState({
msg: 'xixi'
})
},1000)
}
render(){
return (
<Child msg = {this.state.msg} />
);
}
}
class Child extends React.Component {
constructor(props) {
super(props);
}
render(){
return <div>{this.props.msg}</div>
}
}
如果父组件个子组件之间不止一个层级,那么通过 …将父组件的信息传递给更深层级的子组件。
- 子组件传递数据给父组件
子组件向父组件通信同样需要用props,父组件传递一个函数给子组件,子组件调用函数。
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {
msg: 'haha'
}
}
passMsg(msg){
this.setState({
msg: msg
})
}
render(){
return <Child passMsg = {msg => this.passMsg(msg)}/>
}
}
class Child extends React.Component{
constructor(props) {
super(props)
}
componentDidMount(){
setTimeout(() => {
this.props.passMsg('xixi')
},1000)
}
render(){
return <div>子组件向父组件通信</div>
}
}
使用箭头函数 将父组件的passMsg通过props传递给子组件,主要是箭头函数保证了子组件调用函数的时候,函数内部的this仍然指向父组件。
- 对于兄弟组件之间的通信
他们拥有共同的父组件,所以1先向父组件通信,父组件再向2通信,从而实现1和2之间的通信