切换屏幕后,本机保存按钮状态

时间:2018-10-10 04:48:46

标签: javascript reactjs react-native

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

有没有办法即使在更改屏幕后也能保持按钮状态?

任何建议或评论将不胜感激。预先感谢!

2 个答案:

答案 0 :(得分:3)

最好的办法是将状态保存在 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()
    }

答案 1 :(得分:2)

有多种方法可以实现此目的-一种简单的方法可能是使用the 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')
  }
}

希望这会有所帮助!