gpt4 book ai didi

react-native - React Native - 重新安装/重置/重新加载屏幕的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-04 05:13:35 25 4
gpt4 key购买 nike

在 React-Native 中,有没有办法(或多种方式)重新安装或重新加载整个屏幕?

我正在构建一个计算器,如果我遵循这个:
https://facebook.github.io/react-native/docs/refreshcontrol.html

它仍然不会重置输入字段。当然,我可以编写代码来重置屏幕上的每个字段,但是有没有一种通用的方法来刷新屏幕?

例如,如果我只是转到另一个屏幕并返回到该屏幕,则使用导航器,数据将从字段中消失,并且再次全部为 0.0。如何实现?

这是组件的第一个节点,一切都在里面

<ScrollView refreshControl={<RefreshControl
refreshing={this.state.refreshing} onRefresh={this.refreshMe.bind(this)} />}
>
.
.
.
.
.
.
</ScrollView>

谢谢

最佳答案

React 中一个经常使用的 hack 是更改 key支持您的组件以强制重新安装 View :

class Thing extends React.Component {
state = {
uniqueValue: 1
}
forceRemount = () => {
this.setState(({ uniqueValue }) => ({
uniqueValue: uniqueValue + 1
});
}
render() {
return (
<View key={this.state.uniqueValue}>
<Button onPress={this.forceRemount} />
</View>
)
}
}

React 使用元素键来跟踪要更新的元素,如果键被更改,React 会断定之前的元素不再存在,因此将其删除并创建"new"元素。

也就是说,这仅在您要清除的状态存储在子组件树中的有状态组件中时才有效(例如,没有其 TextInput 属性集的 uncontrolled value)。

更清洁的解决方案是制作所有子组件 controlled这样你的组件的 UI 就是它的 props 和 state 的纯函数,只需重置组件状态:

const initialState = {
//...
}

class Thing extends React.Component {
state = initialState;
resetState = () => {
this.setState(initialState);
}
render() {
return (
<View}>
<Button onPress={this.resetState} />
</View>
)
}
}

关于react-native - React Native - 重新安装/重置/重新加载屏幕的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48674827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com