1:没有任何嵌套关系的组件通信(毫无嵌套关系)
利用自定义事件:自定义事件需要借用node.js的events模块1
2
3安装:npm install events --save
引入:import { EventEmitter } from "events";
export default new EventEmitter(); // 初始化实例并输出给其他组件使用
具体的代码示例: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
55
56
57
58
59export default class App extends Component{
render(){
return(
<div>
//这里定义了两个毫无关联的组件,Boo组件向Foo组件传值
<Foo />
<Boo />
</div>
);
}
}
export default class Foo extends Component{
constructor(props) {
super(props);
this.state = {
msg:null,
};
}
componentDidMount(){
// 声明一个自定义事件,接受到msg的参数进行渲染。
this.eventEmitter = emitter.on("callMe",(msg)=>{
this.setState({
msg,
})
});
}
// 组件销毁前移除事件监听
componentWillUnmount(){
emitter.removeListener(this.eventEmitter);
}
render(){
return(
<div>
{ this.state.msg }
我是非嵌套 1 号
</div>
);
}
}
export default class Boo extends Component{
render(){
const cb = (msg) => {
return () => {
// 触发自定义事件。参一为事件名,后面为传递给事件的参数,可多个。
emitter.emit("callMe","Hello")
}
}
return(
<div>
我是非嵌套 2 号
<button onClick = { cb("blue") }>点击我</button>
</div>
);
}
}
2:父组件向子组件传值
父组件通过props向子组件传递需要的信息1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class Child extends Component{
render(){
//这边子组件通过this.props接受到值
const { name } = this.props;
return <p>hello, { name }</p>;
}
}
class Parent extends Component{
render(){
return (
<div>
<Child name='Bob' />
</div>
);
}
}
3:子组件向父组件通信
通过回调函数的方式比较普遍
其原理为:父组件将一个函数作为props传递给子组件,子组件调用这个回调函数,将想要传递的信息,作为参数,传递给父组件。示例如下: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
33class Parent extends Component{
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
this.state={
visible: false。
}
}
handleClick(){
this.setState({
visible: true,
});
}
render(){
return (
<React.Fragment>
<div style={{display: this.state.visible ? 'block' : 'none'}}>
我是被隐藏的文字
</div>
<Child name='Bob' handleClick={this.handleClick} />
</React.Fragment>
);
}
}
class Child extends Component{
render(){
const { handleClick } = this.props;
//子组件拿到父组件的handleClick函数,并将它作为参数返回给父组件,父组件点击会触发对应的效果。
return (<button onClick={handleClick}>点击显示隐藏的文字</button>);
}
}
4:跨级组件通信
对于跨级组件,像爷孙这种传递方式,一般有两种方法:(1)向层层传递props。(2)利用context。
1)这里我比较推荐用this.props层层传递的方式,虽然弊端是对于组件结构较深,比较复杂,但一般情况下可以避免这种嵌套较深的结构。
2)Context就像全局变量一样,而全局变量正是导致应用走向混乱的罪魁祸首之一,给组件带来了外部依赖的副作用,因此,不推荐使用context。其比较好的应用场景是:真正意义上的全局信息且不会更改,如界面主题,用户信息。总体原则是:如果真的需要使用,建议写成高阶组件来实现。
参考资料:React组件间通信