Dav*_*ile 24 javascript react-native
使用React Native中的Redux AddTodo示例.下面的第一个AddTodo示例使用state来存储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}) } } />
);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,遵循一些Redux示例,以下代码要短得多,并且除了TextInput value在提交后不会被清除之外也可以使用
let AddTodo = ({ dispatch }) => {
return (
<TextInput
onSubmitEditing = { e => { dispatch(addTodo(e.nativeEvent.text)) } }
/>
)
}
Run Code Online (Sandbox Code Playgroud)
有什么办法可以清除onSubmitEditing的InputText值吗?
Kaw*_*267 52
将ref添加到TextInput,例如:
<TextInput ref={input => { this.textInput = input }} />
Run Code Online (Sandbox Code Playgroud)
然后调用this.textInput.clear()以清除您的输入值
小智 12
它将提供默认的明文按钮.
<TextInput clearButtonMode="always" />
Run Code Online (Sandbox Code Playgroud)
因为您使用的是功能组件,所以您可以按如下方式使用 Hook。如果您的代码有条件渲染,请检查 todoInput 是否在传递给 useEffect 的函数中定义。我假设您的状态变量在依赖项列表中称为 todoText 。
import {useRef, useEffect} from 'react';
let AddTodo = ({ dispatch }) => {
const todoInput = useRef();
useEffect(()=>todoInput.current.clear(),[todoText]);
return (
<TextInput
ref={todoInput}
onSubmitEditing = { e => { dispatch(addTodo(e.nativeEvent.text)) } }
/>
)
}
Run Code Online (Sandbox Code Playgroud)
我正在使用本机基础 ,这就是我如何使其工作的
constructor(props) {
super(props);
this.searchInput = React.createRef();
}
<Input
placeholder="Search"
ref={this.searchInput}
/>
Run Code Online (Sandbox Code Playgroud)
然后每当我想清除我使用
this.searchInput.current._root.clear();
Run Code Online (Sandbox Code Playgroud)
参考https://github.com/facebook/react-native/issues/18843
一个简单的方法将使用value的属性TextInput和使用组件的状态值对象设置为textInput的价值。
state = {
inputTextValue : '',
}
submitText = () => {
//handle the click action
//add this line at the end of the function after you are done handling with the input text value.
setState({inputTextValue : ''})
}
<TextInput
onChangeText={(text) => this.setState({ inputText: text })}
placeholder="Monday's breakfast"
value={this.state.inputTextValue}
/>
<TouchableOpacity
onPress={() => this.submitText()}>
<Text>Submit</Text>
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)
根据React 16.3之后的更改和建议,您将需要使用React.createRef在构造函数中检索引用:
在构造函数中:
this.myTextInput = React.createRef();
在渲染功能:
<TextInput ref={this.myTextInput} />
然后你可以打电话
this.myTextInput.current.clear();
[1] https://reactjs.org/docs/refs-and-the-dom.html
| 归档时间: |
|
| 查看次数: |
33478 次 |
| 最近记录: |