首先是我的自定义组件。
return (
<View style={[styles.container, this.props.style]}>
<TextField
style={styles.inputText}
autoCapitalize={this.props.autoCapitalize}
ref={this.props.ref}
autoCorrect={false}
onFocus={() => this.setState({isFocus:true})}
onBlur={() => this.setState({isFocus:false})}
value={this.state.text}
label={this.props.placeholder}
secureTextEntry={this.props.secureTextEntry}
blurOnSubmit={this.props.blurOnSubmit}
keyboardType={this.props.keyboardType}
returnKeyType={this.props.returnKeyType}
textContentType={this.props.textContentType}
// onSubmitEditing={this.props.focus(this.props.textInput)}
onSubmitEditing={this.props.onSubmit}
placeholderTextColor='grey'
onChangeText={this.props.onChangeText ? this.props.onChangeText : (text) => this.setState({ text })}
editable={this.props.editable}
/>
</View>
);
现在提交电子邮件字段时,我要使密码字段成为焦点,而提交密码字段时,我要提交表单。
这里是代码:
<MaterialTextInput
placeholder="Email"
// ref={(input) => { this.emailInput = input; }}
ref={ref => (this.emailInput = ref)}
onSubmit = {() => this.passwordInput.focus()}
onChangeText={(text) => this.handleEmailchange(text)}/>
<MaterialTextInput
placeholder="Password"
ref={ref => this.passwordInput = ref}
onSubmit = {() => this.submit()}
onChangeText={(text) => this.handlePasswordchange(text)}/>
但是这不起作用。它给出了错误,
this.passwordInput.focus is undefined
请告诉我我在这里做错了什么?
您不能直接在自定义组件中使用ref
。您必须声明您的自定义组件,如下所示:
const MaterialTextInput = React.forwardRef((props, ref) => {
return (
<View style={[styles.container, this.props.style]}>
<TextField
style={styles.inputText}
autoCapitalize={this.props.autoCapitalize}
ref={ref} // Change Here also
autoCorrect={false}
onFocus={() => this.setState({isFocus:true})}
onBlur={() => this.setState({isFocus:false})}
value={this.state.text}
label={this.props.placeholder}
secureTextEntry={this.props.secureTextEntry}
blurOnSubmit={this.props.blurOnSubmit}
keyboardType={this.props.keyboardType}
returnKeyType={this.props.returnKeyType}
textContentType={this.props.textContentType}
// onSubmitEditing={this.props.focus(this.props.textInput)}
onSubmitEditing={this.props.onSubmit}
placeholderTextColor='grey'
onChangeText={this.props.onChangeText ? this.props.onChangeText : (text) => this.setState({ text })}
editable={this.props.editable}
/>
</View>
)
})
因为<MaterialTextInput>
中的分量this.passwordInput
实际上是<View>
而不是<TextField>
。而且View没有任何名为focus()
的方法!
// Here you are trying to make focus into <View> rather than the <TextField />
return (
<View style={[styles.container, this.props.style]}>
<TextField
...
/>
</View>
)