javascript - 在一个组件中使用值并在另一个组件中重置
问题描述
我有一个简单的 ReactJS 组件,它使用一些状态,myValue
存储在上下文中。
在这个页面上,我myValue
用一些 HTML 和一个按钮呈现。
我希望在 HTML 中呈现的原始值myValue
,但我想将上下文中的值设置为 0。
该按钮应始终显示上下文中保存的值,该值应在页面上呈现为 0。
export function MyComponent() {
const { myValue, setMyValue } = useContext(myValueContext);
useClearData(); // Should be called somewhere to reset myValue to 0
return (
<React.Fragment>
<MyValueButton /> {/* Should display myValue as 0 */}
<main className="App">
<div>
My value is the original {myValue} which should be non-zero!
</div>
</main>
</React.Fragment>
);
}
如何构造此代码,以便在上下文更改时重新呈现按钮,但 HTML 不会?
解决方案
所以,要回答我自己的问题,这需要useRef钩子:
export function MyComponent() {
const { myValue, setMyValue } = useContext(myValueContext);
myValueRef = useRef(myvalue);
useClearData(); // Should be called somewhere to reset myValue to 0
return (
<React.Fragment>
<MyValueButton /> {/* Should display myValue as 0 */}
<main className="App">
<div>
My value is the original {myValueRef.current.toString()} which should be non-zero!
</div>
</main>
</React.Fragment>
);
}
推荐阅读
- python - 如何在 Pandas Python 中为一组主键分组填充 NA 值
- html - 如何将元素对齐到 div 框的右侧?
- android - 从android中的片段更改当前选项卡
- api - 为什么 XHR 请求在实时服务器上永远挂起?
- javascript - 在按下刷新按钮或重定向到另一个页面之前,如何获取网页上经过的总秒数?
- flutter - 如何在后台“变暗”小部件?
- android - 当 android 应用程序打开并具有高优先级时显示 firebase 通知
- angular - 如何在内存中编译角度组件或模板而不注入视图并获取innerHTML?
- python - Ubuntu 18.04 上的 KivyMD 安装错误
- google-chrome - 我或我的应用程序如何知道 Chrome 正在丢弃索引的数据库项目?