【问题标题】:How to check the state of a view in React Native?如何在 React Native 中检查视图的状态?
【发布时间】:2017-09-27 00:25:45
【问题描述】:

我正在尝试在按下按钮时更新视图的backgroundColor。如果颜色是红色,那么我希望它变为橙色,反之亦然。

我目前有按钮将视图从红色更改为橙​​色,但反之则不然。

constructor(props) {
    super(props);
    this.state = {
        viewColour: "red",
    }
}

render() {
    return (
        <View style={styles.parentView}>
            <Button
                title="Press here"
                onPress={() => this.setState({viewColour:"orange"})}
            />

            <View style={Object.assign({}, styles.colourSquare, {backgroundColor: this.state.viewColour})}/>
        </View>
    );
}

如何检查视图的当前颜色以确定按下按钮时将其更改为什么颜色?

【问题讨论】:

    标签: mobile react-native jsx


    【解决方案1】:

    你应该这样做

    render() {
    return (
        <View style={styles.parentView}>
            <Button
                title="Press here"
                onPress={() => this.setState({viewColour: this.state.viewColour == 'red' ? "orange" : 'red'})}
            />
    
          <View style={[styles.colourSquare, {backgroundColor: this.state.viewColour}]}/>
        </View>
      );
    }
    

    【讨论】:

      【解决方案2】:

      虽然 Mohammed 的方法有效,但 Facebook 现在建议在新状态依赖于旧状态 (according to the docs) 时将函数而不是对象传递给 setState。因此你应该这样做this.setState((prevState) =&gt; ({viewColour: prevState.viewColour == 'red' ? "orange" : 'red'}))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多