繁体   English   中英

更改屏幕后,react-native保存按钮状态

[英]react-native save button status after changing screens

我的应用程序中有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()
    }

有许多方法可以实现这一点 - 一种简单的方法可能是使用AyncStorage API来保持按钮的状态,以便在返回到此屏幕时可以恢复它。

所以你可以用这个:

import { AsyncStorage } from "react-native"

然后在_singleTapMultipleSelectedButtons_limited(interest)您可以将以下内容添加到函数的末尾:

AsyncStorage.setItem('button_state',
     JSON.stringify(this.state.multipleSelectedDataLimited));

最后,您将此方法添加到组件中,以从任何持久化的数据初始化按钮状态:

componentDidMount() {
  try {
    // Fetch data from store if it exists
    AsyncStorage.getItem('button_state').then(data => {

      // If data present, try and parse it and restore button state from it
      if(data) {
        const multipleSelectedDataLimited = JSON.parse(data);
        this.setState({ multipleSelectedDataLimited })
      }          
    });
  }
  catch(err){
    console.log('Failed to load button state')
  }
}

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM