javascript - 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
. 知道如何立即渲染吗?
解决方案
你有两种方法。
设置默认状态,
constructor(props) {
super(props)
this.state = {
noteText: '',
userName:'Kevin',
}
this.changeState = this.changeState.bind(this);
}
或来电changeState
,componentDidMount
componentDidMount(){
this.changeState(); //bind this to changeState in constructor
}
推荐阅读
- javascript - javascript中的快速多边形联合
- google-apps-script - 自行组织 Google Apps 脚本
- django - Django - ConnectionAbortedError: [WinError 10053] 已建立的连接被主机中的软件中止
- python - TypeError:“NoneType”对象在 send_mail 中不可迭代?
- android - 如何使用类别显示 Firebase 数据库中的工具栏标题?我被困住了
- powershell - 删除文件夹和文件但排除子文件夹
- javascript - 内联样式 CSP 违规 tawk.to 嵌入式聊天小部件
- .htaccess - htaccess 重定向子目录中的所有文件以重定向到该子目录索引页
- html - 项目在 html 中的分辨率较低的一行中未对齐
- reactjs - 如何使用 React hooks 在 todo 中提交数据