2016-11-11 86 views
0

我试图给我的自定义组件选项使用ref,但我不知道如何去做,最好的方法是做什么?React/React-Native Refs [修正]

<View style={ styles.wrapItems }> 
    <TouchableOpacity onPress={() => this.emailInput.onError() }> 
    <Text>Show Error</Text></TouchableOpacity> 
    <InputField ref={(ref) => this.emailInput = ref } alignItems={'center'} placeholder="Your Email" /> 
    <InputField ref={(ref) => this.passwordInput = ref } 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 
    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} /> 

**我删除了静态函数和它的工作。

+0

你究竟在做什么?访问输入字段的值? – azium

+0

@azium,我在我的组件内部有一个静态函数,我想从外部调用它,但我需要以某种方式来引用此组件。 –

+0

通常在React中使用refs意味着你做错了什么。你可以发布你的组件的静态方法和组件要调用它从?几乎肯定有更好的方法 – azium

回答

1

您需要的裁判参数分配给this.emailInput

<InputField ref={ref => this.emailInput = ref} alignItems={'center'} placeholder="Your Email" /> 

但使用裁判照顾,通常这不是一个好方法(有时道具回调做的工作)。