繁体   English   中英

我如何使用上下文在React中的类和功能组件之间共享状态?

[英]How do I use context to share state between a class and a functional component in react?

我有一个顶级上下文提供程序,其次是一个父类组件,然后是一个功能性无状态子级。

我可以从“子级”更新我的上下文值,但不能从父级更新,即使该值在父级中更新。

如何使用上下文更新和共享两个组件之间的状态?

import React from "react";
import ReactDOM from "react-dom";

const Context = React.createContext();

const Provider = ({ children }) => {
  const [value, setValue] = React.useState(0);
  return (
    <Context.Provider value={{ value, setValue }}>{children}</Context.Provider>
  );
};

const Child = () => {
  const { value, setValue } = React.useContext(Context);
  return <div onClick={() => setValue(value + 1)}>Plus plus!!</div>;
};

class Parent extends React.Component {
  render() {
    const { value, setValue } = this.context;
    return (
      <div>
        <div onPress={() => setValue(value - 1)}>MINUS MINUS!</div>
        <div>{this.props.children}</div>
        <h1>{value}</h1>
      </div>
    );
  }
}
Parent.contextType = Context;

function App() {
  return (
    <Provider>
      <Parent>
        <Child />
      </Parent>
    </Provider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

https://codesandbox.io/s/thirsty-oskar-ocmxr

将“ onPress”更改为“ onClick”即可使用。 我已经测试过了

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM