【发布时间】:2017-03-25 20:45:58
【问题描述】:
我正在尝试为我的自定义组件提供使用 ref 的选项,但我不知道该怎么做,最好的方法是什么?
例如我有我的组件:<InputField ref="email" />
如果我在 InputField 类中执行console.log,我会得到一个空的refs={}
<View style={ styles.wrapItems }>
<TouchableOpacity onPress={() => this.emailInput.onError() }>
<Text>Show Error</Text></TouchableOpacity>
<InputField ref={(ref) => this.emailInput } alignItems={'center'} placeholder="Your Email" />
<InputField ref={(ref) => this.passwordInput } secureTextEntry={true} placeholder="Your Password" />
</View>
在我的组件内部
export default class InputField extends Component {
constructor(props) {
super(props);
}
static onError() {
alert('On Error');
}
return (
<View style={ styles.inputWr }>
<TextInput
ref={??}
style={ [styles.input, textDir, textColor] }
onChangeText={this.onChangeText}
keyboardType={keyboardType}
underlineColorAndroid={'rgba(0,0,0,0)'}
onFocus={this.onFloatLabel}
secureTextEntry={secureTextEntry}
value={this.state.text}
onBlur={this.onFloatLabel} />
【问题讨论】:
-
你到底想做什么?访问输入字段的值?
-
@azium,我的组件中有一个静态函数,我想从外部调用它,但我需要以某种方式引用这个组件。
-
通常在 React 中使用 refs 意味着你做错了什么。您可以使用静态方法和要从中调用它的组件发布您的组件吗?几乎可以肯定有更好的方法
-
@azium,我刚刚添加了一个 sn-p。我不想做任何疯狂的事,哈哈。
-
你试图调用的函数是做什么的? ref 将是对元素而不是类的引用,因此静态函数将不可用。
标签: reactjs react-native components ref