我有一个带有TextInput和Text的组件:
const InputWithMessage = ({ label, formikProps, formikKey,ref, ...rest }) => {
if (formikProps.touched[formikKey] && formikProps.errors[formikKey]) {
styles.inputStyles.borderColor = 'red';
}
return (
<View style={styles.inputStyles}>
<TextField
lineWidth={0}
activeLineWidth={0}
style={styles.textFieldStyles}
label={label}
ref={ref}
tintColor={
formikProps.touched[formikKey] && formikProps.errors[formikKey]
? colors.red
: colors.primary
}
onChangeText={e => formikProps.setFieldValue(formikKey, e)}
onBlur={formikProps.handleBlur(formikKey)}
{...rest}
/> .....
此组件以带引用的formik形式使用,从一个输入到另一个输入:
<View style={{width: '50%',marginRight: 1}}>
<InputWithMessage
formikProps={formikProps}
formikKey="firstName"
value={formikProps.values.firstName}
placeholder="Prénom*"
returnKeyType="next"
ref={this.firstName}
onSubmitEditing={() => {
this.birthName.current.focus()
}}
blurOnSubmit={false}
keyboardType='default'
autoFocus
/> ....
我在构造函数中将这样的引用推到了一起: this.birthName = React.createRef();
除了我的梦想一直都是虚幻的,所以无法集中精力...
有什么想法吗?
答案 0 :(得分:0)
我认为您的焦点召唤是错误的,您需要束缚当前的根源。
因此您需要在onSubmitEditing内部
this.birthName.current._root.focus();
答案 1 :(得分:0)
您应该设置相同的名称。
this.birthName = React.createRef();
...
<TextField
ref={this.birthName}
...
/>
...
<InputWithMessage
...
onSubmitEditing={() => {
this.birthName.current.focus()
}}
...
/>
用法示例 Example Link
import * as React from 'react';
import { Text, View, StyleSheet,TextInput,Button } from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
this.textInput2 = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
this.textInput.current.focus();
}
render() {
return (
<View style={{flex:1,justifyContent:"center",alignItems:"center"}}>
<TextInput ref={this.textInput} style={{width:"80%", height:30,backgroundColor:"blue",color:"#ffffff"}}/>
<TextInput ref={this.textInput2} style={{width:"80%", height:30,backgroundColor:"red",color:"#ffffff"}}/>
<Button title="focus button" onPress={this.focusTextInput}/>
</View>
);
}
}
使用callback ref
或更早版本时,请使用常规React 16.3
。
constructor(props) {
super(props);
this.textInput = null;
this.focusTextInput = () => {
if (this.textInput) this.textInput.focus();
};
}
....
<Text ref={ element => { this.textInput = element}} > </Text>
<Button title="Focus the text input" onPress={this.focusTextInput} />
答案 2 :(得分:0)
您应该使用innerRef
而不是ref
,并且不要忘记使用.current
示例
this.birthName.current._root.focus();