Reputation: 721
I try this
<Input placeholder="search...."
ref={(ref) => { this.SearchInput = ref; }}
/>
<Button transparent onPress={this.clear}>
<Ionicons name="ios-close" />
</Button>
and function:
clear = () => {
this.SearchInput.clear();
}
I get this error:
this.SearchInput.clear() is not a function
Upvotes: 1
Views: 4324
Reputation: 344
i totally agree with Muhammad Hanzala as it worked for me on this but there is a little exception which is really important which i had to do to make it work be sure to add the reference of the text input to your constructor like this:
constructor()
{
...
this.SearchInput = React.createRef();
}
A full example will look like this in your input element...
<InputgetRef={(ref) => this.SearchInput = ref}/>
in your constructor :
constructor()
{
...
this.SearchInput = React.createRef();
}
and finally you can call:
this.SearchInput._root.clear();
and dont forget to clear your state..
Upvotes: 0
Reputation: 321
I use value and state to achieve this functionality
here is the example:
<Input
value={ this.state.value }
onChangeText={ this.onTextChange }
/>
<Button onPress={this.clear}>
<Ionicons name="ios-close" />
</Button>
declare default value
's value on constructor
this.state = {
value: ''
}
listen to onTextChange as follows, this make sure that the value on Input stay the same as we inserting, not blank forever:
onTextChange = (value) => {
this.setState({ value })
}
finally, on clear
function
clear = () => {
this.setState({ value: '' })
}
just set back value
to empty
Upvotes: 3
Reputation: 105
This is the running code, change ref
to getRef
and use this.SearchInput._root.clear();
instead of this.SearchInput.clear();
clear = () => {
this.SearchInput._root.clear();
}
render() {
return (
<Container>
<Header />
<Content>
<Item floatingLabel>
<Input placeholder="search...."
getRef={(ref) => this.SearchInput = ref}
/>
</Item>
<Button onPress={this.clear}>
<Ionicons name="ios-close" />
</Button>
</Content>
</Container>
);
}
Upvotes: 5