首页 > 解决方案 > react-native:如何渲染状态

问题描述

我无法渲染我的state. 我的状态的初始值是empty但是当我按下按钮时state change

我想立即看到这种变化,但state只有renders开始在我的Textinput

这是我的状态:

  constructor(props) {
    super(props)
    this.state = {
      noteText: '',
      userName:'',
  }
}

我使用 onPress 按钮更改状态

changeState(){
this.setState({userName:'Kevin'})
}

这是我渲染状态的地方

    <View>
//I want to immediately render this.state.userName
       <Text>{this.state.userName}</Text>
          <TextInput
                    onChangeText={(noteText) => this.setState({noteText:noteText})}
                    value={this.state.noteText}
                    />
    </View>

在我开始在我的TextInput. 知道如何立即渲染吗?

标签: javascriptreact-native

解决方案


你有两种方法。

设置默认状态,

constructor(props) {
    super(props)
    this.state = {
      noteText: '',
      userName:'Kevin',
  }
  this.changeState = this.changeState.bind(this);
}

或来电changeStatecomponentDidMount

componentDidMount(){
   this.changeState(); //bind this to changeState in constructor
}

推荐阅读