![](/img/trans.png)
[英]Problem with onChangeText whenn using react-native-component this.setState doesnt set state inside onChangeText
[英]this.setState not changing state when using onChangeText React Native
我尝试了一些方法来获取 setState() 来更新 state 的值。 目前<TextInput>
中的文本发生了变化,但this.state
中的值没有变化。
我将console.log
放在正确的位置,我尝试编写外部函数,我弄乱了变量的名称,但似乎没有任何效果。
import * as React from 'react';
import { View, Text, TextInput, TouchableHighlight, Dimensions, StyleSheet } from "react-native";
import PropTypes from "prop-types";
class EditNote extends React.Component{
constructor(props){
super(props)
this.state = {
title: '',
text: '',
id: ''
}
}
// TODO: Change textboxes to match the props from the NoteList
static getDerivedStateFromProps(props){
return(
{...props.route.params}
)
}
render(){
return(
<View style={s.container}>
<View style={s.titleContainer}>
<Text style={s.titleText}>Edit Note</Text>
<View style={{flex: 1}}/>
</View>
<View style={s.inputContainer}>
<TextInput
style={{...s.input, ...s.titleInput}}
autoCapitalize='words'
keyboardAppearance='dark'
placeholderTextColor='#DDD'
onChangeText={(title) => { this.setState({title: title}, () => console.log(this.state)) }}
defaultValue={this.state.title}
/>
<TextInput
style={{...s.input, ...s.textInput}}
autoCapitalize='sentences'
keyboardAppearance='dark'
placeholderTextColor='#DDD'
multiline
onChangeText={(text) => { this.setState({text: text}, () => console.log(this.state)) }}
defaultValue={this.state.text}
/>
</View>
<View style={s.buttonContainer}>
<TouchableHighlight
style={s.backButton}
onPress={() => this.props.nav.navigate('NoteListView')}
underlayColor='#300030'
>
<Text style={s.buttonText}>Cancel</Text>
</TouchableHighlight>
<TouchableHighlight
style={s.addButton}
onPress={() => {
console.log(this.state.note)
this.props.nav.navigate('NoteListView', {note: this.state, mode: 'edit'})
}}
underlayColor='#300030'
>
<Text style={s.buttonText}>Edit</Text>
</TouchableHighlight>
</View>
</View>
)
}
}
export default EditNote
我刚刚意识到这是两个部分的问题。
第一个问题是props.route.params
不受后续render()
调用的影响。 这意味着即使您重新渲染组件,也会使用相同的初始属性。
第二个是getDerivedStateFromProps()
。 每次调用渲染 function 时,它都会在它之前调用getDerivedStateFromProps()
,将 state 设置为初始路由参数。
这个问题可以通过以下方式解决:
render()
function 的开头有点像这样的东西会起作用。 this.props.route.params = undefined
选项 3 是应该如何正确完成事情,但最佳解决方案取决于您的代码如何工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.