reactjs - 在 React 中,有没有办法使用 React Context API 在两侧(双工)的两个组件之间进行通信?
问题描述
我想用另一个组件从一个组件发送和接收状态。有没有使用 React Context API 执行该操作的方法?
注意:我不喜欢使用 Redux。
解决方案
是的,你可以这么做。如果您使用道具,则通过传递一些数据和函数的父组件将实现双向通信。子组件使用该函数与父组件进行通信。同样的事情可以用上下文来完成,只是现在组件不是直接的父子。
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.
}
推荐阅读
- java - Javafx FXML 无法从其他包加载控制器
- python-3.x - 为什么我的 Python 程序没有向控制台打印任何内容?
- java - 如何确保 rxjava 方法并行执行并完成?
- unity3d - Hololens 1 未在 MRTK 场景中检测到空中敲击或其他手势
- qt - 使用 mingw 将 Qt 与 github 操作链接
- haskell - 将从文件中读取的数据保存为全局变量 HASKELL
- avfoundation - 对 AVAsset 进行排序时使用的正确时间范围是多少?
- arrays - 将数据库中的列表分成多个部分(React)
- javascript - 要显示的格式数字,例如。“27.0 °C”使用查询和/或 javascript
- javascript - 在字符串的每一层大括号上插入字符串