javascript - React Native 在 setState 之后不重新渲染

标签 javascript reactjs react-native

我不明白为什么组件在 setState 之后没有重新渲染。我认为绑定(bind) onPress 方法会有所帮助,但事实并非如此。 当我点击 TouchableHighlight 时,它会更改 View 背景颜色,但如果我再次点击它,它就不会再改变。

class Item extends Component{

  state={
    currentColor:"#FFFFF"
  }

  onClick() {
    console.log(this.state.currentColor)
    if (this.state.currentColor=='#FFFFF'){
      color='green'
    } else {
      color='#FFFFF'
    }
    this.setState({currentColor:color})
  }

  render(){
    return (
      <TouchableHighlight onPress={ this.onClick.bind(this) } >
        <View style={[styles.item, {backgroundColor: this.state.currentColor}]}>
          <Text style={styles.title}>{this.props.title}</Text>
        </View>
      </TouchableHighlight>
    );
  }
}

最佳答案

问题似乎是您如何在函数中设置currentColor。按照您的做法并不能保证您将获得适合您的 setStatecurrentColor 值。 React's documentation建议使用提供给 setStatestate 参数:

// no need to bing if you use an arrow function here

onClick = () => {
  console.log(this.state.currentColor);
  this.setState(state => ({
    currentColor: state.currentColor === '#FFF' ? 'red' : '#FFF',
  }));
};

关于javascript - React Native 在 setState 之后不重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59829919/

相关文章:

javascript - 如何缩放 jonitjs 图?

javascript - 如何使用不同的数据将数据多次解析到嵌套 View 中

javascript - React 应用程序在本地系统上加载时间过长

css - 如何在 REACT(包含在 index.js 文件中)中优先选择我的样式表而不是 Bootstrap ?

javascript - react -Redux : How to bind this to a parent container in es6?

react-native - React Native Platform OS 突然不工作

javascript - Jquery问题: uncaught SyntaxError: unexpected identifier

javascript - 设置 Facebook 像素以在点击事件时触发

javascript - React-Native将从 url 获取的 JSON 对象分配给变量

react-native - 单选按钮在 Native-Base 中不起作用