I am trying to access a Text Input of a React-native component from a function which in out of the component. I want to clear TextInput through refs in clearForm() function.
MyComponent.js
import React, { Component } from 'react'; import { View, TextInput, } from 'react-native'; class myComponent extends Component { render() { return ( <View style={styles.container}> <TextInput ref= {'email'} style={styles.input} placeholder="Email" /> </View> ); } }
Actions.js
function clearForm(data){ for(var input_name in data){ /////??? //this.refs[input_name].setNativeProps({text: ''}); } }
I'm sorry for taking so long, but this should work:
// myComponent.js
class myComponent extends Component {
constructor(props) {
this.state = {
emailText: ''
}
}
clearField() {
this.setState({
emailText: ''
})
}
render() {
return (
<View style={styles.container}>
<TextInput
ref= {'email'}
style={styles.input}
placeholder="Email"
value={this.state.emailText}
/>
</View>
);
}
}
// Actions.js
function clearForm(data){
for(var input_name in data){
this.refs[input_name].clearField();
}
}
You'll need to set the ref attribute to a function. Check out the documentation here:
https://facebook.github.io/react-native/docs/direct-manipulation.html
ref={ input => this.myInput = input }
There is actually an example of this specifically in that doc: https://snack.expo.io/?session_id=snack-session-HylUL01kbf
尝试使用组件引用名称作为道具,如下所示:
this.refs.email.setNativeProps({text: ''});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.