组件通信 context"/>
react(六)跨(爷孙)组件通信 context
跨组件通信 context
React.createContext(defaultValue)
;
{ Consumer, Provider } = createContext(defaultValue)
Context.Provider
在父组件调用 Provider 传递数据- value 要传递的数据
- 接收数据
class.contextType = Context
;static contextType = Context
;this.context
;
Context.Consumer
<Consumer>{(props)=>{console.log(props);return <div></div>}} </Consumer>
注意在使用不熟练时,最好不要再项目中使用 context,context一般给第三方库使用
创建context.js
import {createContext} from "react";
const context = createContext();
const {Provider,Consumer} = context;
export {Provider,Consumer}
export default context;
父组件:App.js
import React,{ Component } from "react";
import Child from "./Child";
import {Provider} from "./context";
class App extends Component {state={name:"xiaochen"}setName=(newName)=>{this.setState({name: newName})}render(){let {name} = this.state;return <div><Providervalue={{name: name,setName:this.setName }}><Child /></Provider></div>}
}
export default App;
子组件:Child.js(调用了组件subchild.js)
import React,{ Component } from "react";
import SubChild from "./subchild";
class Child extends Component {render(){return <SubChild />}
}
export default Child;
孙组件:subchild.js
import React, { Component } from "react";
import context, { Consumer } from "./context"
class SubChild extends Component {state = {count: 1}render() {let { count } = this.state;return <Consumer>{(context) => {console.log(context);return <div><p>name:{context.name}</p><p>count:{count}</p><button onClick={() => {this.setState(function () {count++;return {count}})}}>递增</button><button onClick={() => {context.setName("小陈");}}>中文名</button></div>}}</Consumer>}
}
SubChild.contextType = context;
export default SubChild;
孙组件采用私有属性的方式接收数据
import React, { Component } from "react";
import context from "./context"class SubChild extends Component {state={count: 1}static contextType = context;render(){let {count} = this.state;console.log(this.context);return <div><p>name:{this.context.name}</p><p>count:{count}</p><button onClick={()=>{this.setState(function(){count++;return {count}})}}>递增</button><button onClick={()=>{this.context.setName("小陈");}}>中文名</button></div> }
}
export default SubChild;
更多推荐
react(六)跨(爷孙)组件通信 context
发布评论