1. 方式一:父子组件之间, 通过props通信
1). 通过props可以传递一般属性和函数属性,
2). 父组件向子组件 ==》通过绑定属性的方式传递props
3). 子组件向父组件通信==》通过调用父组件给子组件传递过来的方法,来与你组件通信>
4). 缺点:只能一层一层传递
兄弟组件必须借助公用的父组件来实现通信。
2. 方式二: 祖先元素与后代元素的数据通信-----通过Context
实现跨层级
2.1、调用方式:
React context提供了Provider和Customer,
在顶层的Provider中传入value,
在子孙级的Consumer中获取该值,并且能够传递函数,用来修改context。
//创建Context组件
const ThemeContext = React.createContext({
theme: 'dark',
toggle: () => {}, //向上下文设定一个回调方法
});
//运行APP
class App extends React.Component {
constructor(props) {
super(props);
this.toggle = () => { //设定toggle方法,会作为context参数传递
this.setState(state => ({
theme:
state.theme === themes.dark
? themes.light
: themes.dark,
}));
};
this.state = {
theme: themes.light,
toggle: this.toggle,
};
}
render() {
return (
<ThemeContext.Provider value={this.state}> //state包含了toggle方法
<Content />
</ThemeContext.Provider>
);
}
}
//中间组件
function Content() {
return (
<div>
<Button />
</div>
);
}
//接收组件
function Button() {
return (
<ThemeContext.Consumer>
{({theme, toggle}) => (
<button
onClick={toggle} //调用回调
style={{backgroundColor: theme}}>
Toggle Theme
</button>
)}
</ThemeContext.Consumer>
);
}
2.2、React context的局限性
- 在组件树中,如果中间某一个组件
ShouldComponentUpdate returning false
了,会阻碍 context 的正常传值,导致子组件无法获取更新。 组件本身 extends React.PureComponent
也会阻碍 context 的更新。
2.3、注意点:
- Context 应该是唯一不可变的
- 组件只在初始化的时候去获取 Context
3. 方式三: 消息订阅-发布模式
发布者发布事件,订阅者监听事件并做出反应,我们可以通过引入 event模块进行通信
1). 实现库: pubsub-js
2). 组件A: 发布消息(相当于触发事件)
3). 组件B: 订阅消息, 接收消息, 处理消息(相当于绑定事件监听)
4). 优点: 对组件关系没有限制
4. 方式四: 使用redux或Mobx全局状态管理工具,这种工具一般会维持一个全局状态中心Store,根据不同的事件产生不同的状态
1). 通过redux可以实现任意组件间的通信
2). 集中式管理多个组件共享的状态, 而pubsub-js并不是集中式的管理
3). store:保存数据的地方。整个应用智能有一个 Store。其中,
- state:包含所有数据,一个 state对应一个view。
- action:view发出的通知 通过action,改变 state,从而改变view。
修改 state的唯一办法是使用 action
参考链接:http://www.atguigu.com/mst/html/gp/17640.html