import React from 'react';
import ReactDom from 'react-dom';
`/**
- 使用跨组件通信 contentText (上下文)
-
- 步骤1: const ContentText = React.createContext()
-
- 步骤2: const { Provider } = ContentText
-
- 步骤3: 使用 这里是想要传递参数的作用域 包裹想要传递参数的作用域组件
-
- 步骤4: 在子组件 使用 static contentType = ContentText
-
- 步骤5: 直接在子组件 this.context.xxx */`
// 1. 创建 上下文
const ContentText = React.createContext();
// 2. Provider 和 Consumer
const { Provider, Consumer } = ContentText;
class App extends React.Component {
state = {
nums: 999,
};
// 处理函数
handelSum = (nums) => {
this.setState({
nums,
});
};
render() {
return (
<div style={{ border: '1px solid #ccc' }}>
<Provider value={{ nums: this.state.nums, handelSum: this.handelSum }}>
<h1>
父组件--{this.state.nums}
<Sub />
</h1>
</Provider>
</div>
);
}
}
// 子组件
class Sub extends React.Component {
render() {
return (
<div style={{ border: '1px solid #ccc' }}>
<h2>
Sub子组件
<Child />
</h2>
</div>
);
}
}
// 函数组件-- 使用 Consumer 包裹 子组件,在 <Consumer>{ 这里需要使用 大括号包裹 (data) => 返回的标签 }</Consumer>
const Child = () => (
<Consumer>
{(data) => (
<div style={{ border: '1px solid #ccc' }}>
<h3 onClick={data.handelSum.bind(null, data.nums + 1)}>
Child-孙组件--{data.nums}
</h3>
</div>
)}
</Consumer>
);
ReactDom.render(<App />, document.querySelector('#root'));