我正在尝试从组件外部的函数访问React-native组件的文本输入。我想通过 clearForm()函数中的refs清除TextInput。
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: ''});
}
}
答案 0 :(得分:1)
我很抱歉花了这么长时间,但这应该有效:
// 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();
}
}
答案 1 :(得分:0)
您需要将ref属性设置为函数。查看文档:
https://facebook.github.io/react-native/docs/direct-manipulation.html
ref={ input => this.myInput = input }
实际上,该文档中有一个例子:https://snack.expo.io/?session_id=snack-session-HylUL01kbf
答案 2 :(得分:0)
尝试使用组件引用名称作为prop,如下所示:
this.refs.email.setNativeProps({text: ''});