简体   繁体   English

为什么 state 上的 React Native 组件不重新渲染

[英]Why doesn't React Native component rerender on state change

I want to dynamically change display property of an element.我想动态更改元素的display属性。 I created a component, but it doesn't rerender, when state is updated.我创建了一个组件,但是当 state 更新时,它不会重新渲染。 I know that function toggleDisplay executes, as it logs displayState to the console.我知道 function toggleDisplay执行,因为它将displayState记录到控制台。 What am I missing?我错过了什么?

  class DetailedInfo extends Component {

    constructor(props) {
      super(props);
   
      this.state = {
        displayState: 'flex',
      };
    }

      toggleDisplay = () => {
          if (this.state.displayState=='flex') {
              this.setState(state => ({displayState: 'none'}))
          } else {
            this.setState(state => ({display: this.state.toggleDisplay}))
          }

          console.log(this.state.displayState);
          this.forceUpdate()
      }

      render() {
        return (
              <ScrollView>
                  <TouchableWithoutFeedback onPress={this.toggleDisplay}>
                      <View style={{backgroundColor: 'blue', height: 500}}>
                          <Text style={{display: 'flex'}}>
                          Lorem Ipsum
                          </Text>
                      </View>
                  </TouchableWithoutFeedback>
              </ScrollView>
        )
      }
  };
  1. you are not using the state variable for style您没有使用 state 变量作为样式

<Text style={{display: this.state.dispalyState }}>

  1. Change toggle display method slightly稍微改变切换显示方法
  toggleDisplay = () => {
      if (this.state.displayState=='flex') {
          this.setState({displayState: 'none'})
      } else {
        this.setState({displayState: 'flex'}))
      }

      console.log(this.state.displayState);
      this.forceUpdate()
  }

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

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