Clear React Native TextInput



在 React Native 中完成 Redux AddTodo 示例。下面的第一个 AddTodo 示例使用状态来存储文本输入值并且工作正常。

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 示例之后,以下代码要短得多,除了提交后未清除TextInputvalue之外,还可以工作

let AddTodo = ({ dispatch }) => {
return (
<TextInput 
onSubmitEditing = { e => { dispatch(addTodo(e.nativeEvent.text)) } } 
/>
)
}

有什么方法可以从提交编辑中清除输入文本值吗?

将 ref 添加到您的 TextInput,例如:

<TextInput ref={input => { this.textInput = input }} />

然后调用this.textInput.clear()以清除输入值

对于 iOS,它将提供默认的明文按钮。

<TextInput clearButtonMode="always" />

查看文档

根据 React 16.3 之后的更改和建议,您需要使用 React.createRef 在构造函数中检索 ref:

在构造函数中:this.myTextInput = React.createRef();

在渲染函数中:

<TextInput ref={this.myTextInput} />

然后你可以打电话

this.myTextInput.current.clear();

[1] https://reactjs.org/docs/refs-and-the-dom.html

我正在使用本机基础这是我如何让它工作

constructor(props) {
super(props);
this.searchInput = React.createRef();
}
<Input
placeholder="Search"
ref={this.searchInput}
/>

然后每当我想清除时,我都会使用

this.searchInput.current._root.clear();

参考 https://github.com/facebook/react-native/issues/18843

一种更简单的方法是使用TextInputvalue属性,并使用组件的状态值对象来设置 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.
this.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>

因为你使用的是函数组件,所以你可以按如下方式使用 Hooks。 如果您有条件渲染您的代码,请检查 todoInput 是否在传递给 useImpact 的函数中定义。 我假设您的状态变量在依赖项列表中称为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)) } } 
/>
)
}

这对我有用

ref={element => {  
//Clear text after Input
this.attendee = element
}}
onSubmitEditing={this.handleAddPress}

this.attendee.setNativeProps({ text: '' })//输入后清除文本

React-Native Using input-component from native-base。 这对我有用:

<Input ref={input => {this.textInput = input;}}

然后:

this.textInput._root.clear();

注意:不必使用 React.createRef(( 进行初始化。

以下代码示例:

<TextInput 
onChangeText={(text) => this.onChangeText(text)} 
ref={component => this._textInput = component}
onSubmitEditing={() => {
this.clearText()
}}
/>
clearText(){
this._textInput.setNativeProps({ text: ' ' });
setTimeout(() => {
this._textInput.setNativeProps({ text: '' });
},3);
}

这对我有用。

在构造函数中初始化 myTextInput:

this.myTextInput = React.createRef();

在渲染函数中添加引用:

<Input ref={this.myTextInput} />

然后你可以打电话

this.myTextInput.current.value='';

在我的函数组件上,我调用另一个函数以及提交处理程序,该函数将注意清除文本

const [text, setText] = useState('');
const anotherFunc = (val) =>{
setText('');
}

return (
<View>
<TextInput 
value ={text}
onChangeText ={changeHander}
placeholder = 'Add '
/>
<Button 
title = "Add Something "
onPress = {()=>  {submitHandler(text) , anotherFunc(text)}}
/>
</View>
)

感谢 Abboud @André 在您的帮助下,我能够清除我的 TextInput 字段,但根据我的自定义 TextInput,我在实现方面做了轻微的更改。

请查看用于实现的代码和方法。据我所知,我现在清除文本输入的要求已经满足,如果需要任何更改,请在评论中通知。

我为使其工作所做的是:

在设置发件人中.js

...
this.state = {
clearInput: false,
...
}
...           
setupSenderSubmit = () => {
...
this.setState({                             
clearInput: !this.state.clearInput,
})
...
}
...
<CustomTextInput
labelText="First Name" 
onChangeText={(firstName) => this.setState({ firstName })}
clearInput={this.state.clearInput}
value={this.state.firstName}
returnKeyType={ 'next' }
autoFocus={true}
onSubmitEditing={() =>  this.input2.current.focus()}
></CustomTextInput>
...

在自定义文本输入中.js

this.state={
clearInput: this.props.clearInput, 
}
...
static getDerivedStateFromProps = (props, state) => { 
if (props.clearInput !== '' || props.clearInput !== undefined) {
return {
clearInput: props.clearInput
}
}
return null;
}
...
<TextInput 
label={this.props.label} 
value={!this.state.clearInput ? this.state.text : null}
onChangeText={(text) => {
this.setState({text});
this.props.onChangeText(text)
}
}
</TextInput>
...

只是为了最近的答案,我使用的是RN CLI 0.70.6和React 18.1.0。我没有使用世博会

const input = useRef(null)
<TextInput
ref={input}
onSubmitEditing={e => {
//do something here e.g. console.log(e.nativeEvent.text)
input.current.clear();
}
/>

触发器将是当您按"Enter"时,它将重定向您或执行您指定的任何操作,并清除当前输入。

我制作此代码是为了清除 React NativeOnSubmitEditing中的文本输入 你可以检查我的零食: https://snack.expo.io/@andreh111/clear-textinput-onsubmitediting

这是代码:

state = {
searchInput:'',
clearInput:false
}
render(){
return(

<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<TextInput 
style={{
borderColor:'black',
borderWidth:1,
width:200,
height:50
}}
onChangeText={(searchInput)=>this.setState({
searchInput
})}
value={!this.state.clearInput ? this.state.searchInput : null}
onSubmitEditing={()=>{
this.setState({
clearInput:!this.state.clearInput,
})
}}
/>
</View>
)
}
<TextInput
ref={input => { this.name = input }}
/>
this.name.clear();
this.email.clear();
this.password.clear();
this.confirmPassword.clear();
this.state = {
commentMsg: '',
}
after submittion 
if (response.success)
{
this.commentMsg.clear();        //TODO me
}

<TextInput
style={styles.textInput}
multiline={true}
ref={input => {
this.commentMsg = input
}}
onChangeText={(text) => this.setState({commentMsg: text})}
placeholder ='Comment'/>

对我有用...

<TextInput
ref={ref => {
this.textInput = ref;
}}
...
/>

呼叫后功能

clearMsg(){
this.textInput.state.value = ''
}

您也可以将<TextInput/>的值设置为与状态相同,并在使用数据后,将状态设置回空字符串:

//state
const [state, setState] = useState({
name: '',
lastname: ''
})
//functions
const newUser = () => {
// Do your magic and after
setState({
name: '',
lastname: ''
})
}
const handleOnChange = () => {
setState({
// change your state
})
}
//render
<TextInput
value={state.name}
placeholder='Name'
onChangeText={/* execute your handleOnChange() */}
/>
<TextInput
value={state.lastname}
placeholder='Lastname'
onChangeText={/* execute your handleOnChange() */}
/>
<Button title='Saved' onPress={() => newUser()} />

希望有用!

对于 RN> 0.6

const [msg, setMsg] = useState()

在文本输入中使用值

<TextInput 
onChangeText={(txt) => setMsg(txt)}}
value={msg}
/>

然后在按钮按下功能中设置状态,如下所示

const pressButton = () => {
setMsg('')
}