Reputation: 943
I'm trying to give my custom component the option to use ref, but I'm not sure how to do it, what would be the best way to do that?
For example I have my component: <InputField ref="email" />
If I do console.log
inside the InputField class, I get an empty 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>
Inside my Component
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} />
Upvotes: 0
Views: 425
Reputation: 38697
Solution by OP.
I changed the static function to a non-static one and it worked.
From:
static onError() {
To:
onError() {
Upvotes: 0
Reputation: 359
You need to assign the ref parameter to this.emailInput
<InputField ref={ref => this.emailInput = ref} alignItems={'center'} placeholder="Your Email" />
But take care using refs, normally it's not a good approach (sometimes props callbacks do the job).
Upvotes: 1