4. 跨组件通信- Context
/* 使用Context来跨组价通信,让App组件-直接传数据给SonSon组件 */ import React, { Component } from 'react'; // 1. 创建Context, 解构两个组价Provider Consumer const { Provider, Consumer } = React.createContext(); export default class App extends Component { render() { return ( // 2. 使用Provider包住子组件 // 3. 给Provider组件设置value属性,传数据 <Provider value="hello React"> <div> <h1>父组件</h1> <Son></Son> </div> </Provider> ); } } class Son extends Component { render() { return ( <div> <h2> 儿子</h2> <SonSon></SonSon> </div> ); } } class SonSon extends Component { render() { return ( // 4. 使用Consumer组件接收数据 <div> <h2> 孙子</h2> <Consumer> {(data) => { return <h1>123 - {data}</h1>; }} </Consumer> </div> ); } }
-
通过组件双标签中间区域,也可以向子组件传递数据,子组件可以通过props.children接收
-
import React, { Component } from 'react';
export default class App extends Component {
render() {
return (
<div>
<Child>夹在组件标签中间的内容</Child>
<Child>
<i>这是一段jsx,使用了i标签</i>
</Child>
<Child2>{() => alert('组件标签中间也可以传递函数')}</Child2>
</div>
);
}
}
function Child({ children }) {
return <h1>child组件的-----{children}</h1>;
}
function Child2({ children }) {
return (
<h1>
child2组件传递的函数,点击按钮触发
<button onClick={children}>点我触发</button>
</h1>
);
}
浙公网安备 33010602011771号