typescript - 布局上的组件文本内容更新
问题描述
我正在使用 Typescript,并且我有这个(功能性)React Native 组件:
export default function BasicView(props: BasicViewProps): ReactElement {
const wRef = useRef<number>(0);
function onLayout(event: LayoutChangeEvent) {
const {width} = event.nativeEvent.layout;
wRef.current = width;
console.log('wRef: ' + wRef.current);
}
return (
<View
onLayout={onLayout}
style={{
width: "100%",
justifyContent: "center",
alignItems: "center",
backgroundColor: "darkgray",
}}
>
<Text style={{ color: "white" }}>{wRef.current}</Text>
</View>
);
}
一切似乎都在使用我的onLayout
代码。我的问题是组件中的内容<Text/>
(打算打印出来wRef.current
)没有更新;当前0
已打印并且永远不会更改。我想我部分理解为什么它没有更新,但我的问题是如何让它更新为wRef.current
?
对于它的价值,我不打算频繁更新这个组件,但我只需要一次更新即可获得 View 布局宽度的初始值。
解决方案
我已经尝试过了,它似乎正在工作
export default function App() {
const wRef = React.useRef(0);
const [width, setwidth] = React.useState("")
function onLayout(event: LayoutChangeEvent) {
const {width} = event.nativeEvent.layout;
wRef.current = width;
setwidth(width)
console.log('wRef: ' + wRef.current);
}
return (
<View
onLayout={onLayout}
style={{
width: "100%",
justifyContent: "center",
alignItems: "center",
backgroundColor: "darkgray",
}}
>
<Text style={{ color: "white" }}>{width}</Text>
</View>
);
}
关于您的问题,我从未尝试过打印 ref 值,但您的问题看起来像是关于状态的初始值,我已经通过更新额外的 useState 来解决此类问题,只是为了更新状态。
推荐阅读
- python - GridSearchCV 和 Google colab:n_jobs=-1 不起作用
- java - 如何在springboot注释中的这3个字段类型Date之间进行约束验证?
- javascript - 从 Messenger 或 MetaMask 打开我的 Web 应用程序时出现黑屏
- sql - SQL 查询 - 选择多个结果作为列字段
- javascript - JS 递归嵌套 JSON 数组子节点加入键
- python - 使用 pyinstaller 的站点包路径
- outlook - 从 slack 的工作区/频道接收 Outlook 的电子邮件并重定向到每个 repo
- flutter - 当父 BlocBuilder 重建时 Flutter 重建 BlocBuilder
- android - 如何在分页 3 库 android 的 PagingData 中添加多个项目?
- python - 如何通过调用其他函数的函数传递参数?