我在React Native应用中拥有一个带有TextInput的屏幕。当TextInput的默认值发生变化时,我调用了componentDidUpdate生命周期。
public componentDidUpdate() {
if (this.props.login) {
this.vm.loginOnChange(this.props.login);
}
}
之后就无法编辑TextInput的值了。
<TextInput
value={this.props.login}
onChange={this.props.loginOnChange}
/>
onChange事件是有效的,但无法改变值。谁能知道如何解决这个问题?
肯定是不行的,看起来很有线。如果你想实现这样的东西,你可以用这样的方法。
class App extends Component {
constructor(props) {
super(props);
this.state = { text: "" }; //declare a state named text
}
componentDidUpdate(prevProps, prevState) {
if (this.props.login!== prevProps.login) {
this.setState({ text: this.props.login });//if this.props.login just true or false , put your text instead(and change the condition as you want), then setstate to update new text
}
}
render() {
return (
<View style={styles.app}>
<TextInput
style={{ height: 40, borderColor: "gray", borderWidth: 1 }}
onChangeText={textchange => this.setState({ text:textchange })} //control the text value
value={this.state.text} //receive the text with state change will update
/>
</View>
);
}
}
按照这个方法 例子 会更容易。
我的问题是在componentDidUpdate,我做了这个。
public componentDidUpdate(prevProps: Props) {
if (!!this.props.login && this.props.login !== prevProps.login) {
this.loginOnChange(this.props.login);
}
}
现在可以用了!