在 React Native 中完成 Redux AddTodo 示例。下面的第一个 AddTodo 示例使用状态来存储 TextInput 值并且工作正常。
class AddTodo extends React.Component{
constructor(props){
super(props);
this.state = { todoText: "" };
}
update(e){
if(this.state.todoText.trim()) this.props.dispatch(addTodo(this.state.todoText));
this.setState({todoText: "" });
}
render(){
return(
<TextInput
value = {this.state.todoText}
onSubmitEditing = { (e)=> { this.update(e); } }
onChangeText = { (text) => {this.setState({todoText: text}) } } />
);
}
}
然而,在一些 Redux 示例之后,以下代码更短并且也可以工作,除了 TextInput
value
在提交后未被清除
let AddTodo = ({ dispatch }) => {
return (
<TextInput
onSubmitEditing = { e => { dispatch(addTodo(e.nativeEvent.text)) } }
/>
)
}
有什么方法可以清除 onSubmitEditing 中的 InputText 值吗?
原文由 Dave Pile 发布,翻译遵循 CC BY-SA 4.0 许可协议
将 ref 添加到您的 TextInput,例如:
然后调用
this.textInput.clear()
清除您的输入值