|
本帖最后由 周大胖子 于 2022-4-28 11:01 编辑
context的局限性:
虽然可以实现跨组件通讯,但是通过context 只能实现从上往下传递,不能实现从下往上传递或者同级之间传递
-
- import React from "react";
- // 1.创建一个上下文对象
- const AppContext2 = React.createContext({
- name:'林志玲',
- age:45
- });
- // 2.从上下文对象中获取容器组件
- // Provider: 生产容器组件
- // Consumer: 消费者容器组件
- // 容器组件:专门用于包裹其他组件的组件
- const { Provider, Consumer } = AppContext2;
- class RightDiv extends React.Component {
- constructor() {
- super();
- }
- render() {
- return (
- <section>
- <p>演员2:{this.context.name}</p>
- <p>年龄2:{this.context.age}</p>
- </section>
- )
- }
- }
- // 通过静态方法 来消费 数据 如果有多个生产者 不能用这种模式
- RightDiv.contextType = AppContext2;
- class LeftDiv extends React.Component {
- constructor() {
- super();
- }
- render() {
- return (
- <section>
- 这是父组件
- <br />
- <RightDiv></RightDiv>
- </section>
- )
- }
- }
- class ContextTemp extends React.Component {
- constructor() {
- super();
- }
- render() {
- return (
- <section>
- 这是爷爷辈的组件
- <LeftDiv></LeftDiv>
- </section>
- )
- }
- }
- export default ContextTemp;
复制代码
上面是简写:其实我觉得用的地方不会很多
|
|