我使用 useRef 而不是 useState。但是我的 btn 名稱沒有改變。為什么 ?
const data = useRef(null);
const handlePressCategory = (category: Categories) => {
data.current = category;
modalCategoriesRef.current?.close();
}
<Pressable style={[ButtonStyles.full_without, s.btn]} onPress={handleOpenModalCategories}>
<Text style={s.btnText}>{ data.current === null ? 'Kategorie ausw?hlen' : data.current}</Text>
</Pressable>
我非常感謝您的幫助和回答。我不知道為什么它不顯示
uj5u.com熱心網友回復:
更改資料useRef不會觸發 React 重新呈現您的視圖。把它想象成課堂上的某個領域,你可以在沒有任何反應的情況下改變它。
https://reactjs.org/docs/hooks-reference.html#useref
如果您在ref發生更改時需要重新渲染視圖,只需使用useState. 它是專門為它設計的
否則,如果不可能,您可以撰寫一些useForceRerender掛鉤來呼叫組件的渲染。像這樣的東西:
export const useForceRerender = () => React.useReducer((x) => x 1, 0)[1];
const App = () => {
const data = useRef(null);
const forceRerender = useForceRerender();
const handlePressCategory = (category: Categories) => {
data.current = category;
modalCategoriesRef.current?.close();
forceRerender(); // <-- here
}
return (
<Pressable style={[ButtonStyles.full_without, s.btn]} onPress={handleOpenModalCategories}>
<Text style={s.btnText}>{ data.current === null ? 'Kategorie ausw?hlen' : data.current}</Text>
</Pressable>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/522566.html
標籤:反应反应式
下一篇:如何知道警報是否彈出?
