首页 > 解决方案 > 在 React 中,有没有办法使用 React Context API 在两侧(双工)的两个组件之间进行通信?

问题描述

我想用另一个组件从一个组件发送和接收状态。有没有使用 React Context API 执行该操作的方法?

注意:我不喜欢使用 Redux。

标签: reactjsreact-context

解决方案


是的,你可以这么做。如果您使用道具,则通过传递一些数据和函数的父组件将实现双向通信。子组件使用该函数与父组件进行通信。同样的事情可以用上下文来完成,只是现在组件不是直接的父子。

export const ExampleContext = React.createContext();

const ExampleProvider = (props) => {
  const state = useState('something');

  return (
    <ExampleContext.Provider value={state}>
      {props.children}
    </ExampleContext.Provider>
  )
}

const ExampleConsumer = (props) => {
  const [value, setValue] = useContext(ExampleContext);

  // Do something with the value, or call setValue to let the provider know it needs to update.
}

推荐阅读