react(六)跨(爷孙)组件通信 context

编程入门 行业动态 更新时间:2024-10-06 06:45:46

react(六)跨(爷孙)<a href=https://www.elefans.com/category/jswz/34/1771375.html style=组件通信 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

本文发布于:2024-02-28 09:33:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1768805.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   通信   react   爷孙   context

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!