javascript - 更改屏幕后反应本机保存按钮状态
问题描述
我的应用程序中有 5 个按钮 [“跑步”、“骑行”、“阅读”、“编码”、“牛儿”],当我点击它时,按钮会改变颜色并在屏幕上显示标题。我正在使用这个库:react-native-selectmultiple-button。
假设我单击了“跑步”和“骑行”按钮,这些按钮将突出显示,并且文本将显示在屏幕上,但是当我将屏幕更改为另一个页面并返回到上一个屏幕时,按钮状态设置回默认值。
下面是我的代码:
const multipleData = ["running", "riding", "reading", "coding", "Niuer"];
export default class SimpleButton extends Component {
constructor(props) {
super(props);
this.state = {
multipleSelectedDataLimited: []
};
}
render() {
return (
<View style={{paddingTop:200}}>
<Text style={styles.welcome}>
implement the multiple-select buttons demo by SelectMultipleButton
</Text>
<Text style={{ color: 'blue', marginLeft: 10 }}>
I like {_.join(this.state.multipleSelectedDataLimited, ", ")}
</Text>
<View
style={{
flexWrap: "wrap",
flexDirection: "row",
justifyContent: "center"
}}
>
{multipleData.map(interest => (
<SelectMultipleButton
key={interest}
buttonViewStyle={{
borderRadius: 10,
height: 40
}}
textStyle={{
fontSize: 15
}}
highLightStyle={{
borderColor: "gray",
backgroundColor: "transparent",
textColor: "gray",
borderTintColor: 'blue',
backgroundTintColor: 'blue',
textTintColor: "white"
}}
value={interest}
selected={this.state.multipleSelectedDataLimited.includes(
interest
)}
singleTap={valueTap =>
this._singleTapMultipleSelectedButtons_limited(interest)
}
/>
))}
</View>
</View>
);
}
_singleTapMultipleSelectedButtons_limited(interest) {
if (this.state.multipleSelectedDataLimited.includes(interest)) {
_.remove(this.state.multipleSelectedDataLimited, ele => {
return ele === interest;
});
} else {
if (this.state.multipleSelectedDataLimited.length < 3)
this.state.multipleSelectedDataLimited.push(interest);
}
this.setState({
multipleSelectedDataLimited: this.state.multipleSelectedDataLimited
});
}
}
const styles = StyleSheet.create({
welcome: {
margin: 10,
marginTop: 30,
color: "gray"
}
});
即使在更改屏幕后,有没有办法保持按钮的状态?
任何建议或意见将不胜感激。提前致谢!
解决方案
你能做的最好的事情就是在Redux中保存你的状态并使用redux-persist。您还可以使用AsyncStorage。我有类似的情况,我必须保持两个组件之间来回导航的状态,我使用了这样的导航参数:
屏幕 A:
this.props.navigation.navigate('ScreenB', {
onPressScreenAFun: (params) => {
this.screenAFun(params),
ButtonState1: true // you can send multiple params
},
})
screenAFun = (ButtonState1) => {
this.setState({buttonState1: ButtonState1})
}
屏幕 B:
screenBFun = (params) => {
const { onPressScreenAFun, ButtonState1 } = this.props.navigation.navigate.state.params
onPressScreenAFun(ButtonState1)
this.props.navigation.goBack()
}
推荐阅读
- git - 在 git hub 中克隆大项目
- javascript - 如何使用 Flow 要求特定对象
- android - 如何在 CoordinatorLayout 中的 AppBarLayout 下面制作 ViewStub
- ruby-on-rails - 如果用户编辑该字段,建议按钮应显示消息。如何?
- laravel - 如何在 Laravel 中使用 eloquent 从子表中获取价值?
- clojure - 增加一个原子的值
- r - Rcpp:NumericVector 输入和输出改变原始输入数据,但 IntegerVector 不会
- python - Python - Pandas DF - 基于 2 个或更多列创建具有唯一值的 DataFrame
- c - 用于评估除 main 以外的函数中的字符串时,sizeof 结果的差异
- reactjs - Typescript + Reactjs - 导入的 svg 不呈现