简体   繁体   English

具有两个 TextInput 元素时反应 Native 焦点问题

[英]React Native focus issue when having two TextInput elements

I have two InputField components that I have created using TextInput :我有两个使用TextInput创建的InputField组件:

<KeyboardAvoidingView
  behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
>
  <View>
    <InputField
      value={value1}
      onChangeText={onVal1Change}
    />
    <InputField
      value={value2}
      onChangeText={onVal2Change}
    />
  </View>
</KeyboardAvoidingView>

And this is the code for the InputField component:这是InputField组件的代码:

const [isFocus, setIsFocus] = useState<boolean>(false);
const inputRef = useRef<TextInput>(null);

const onPress = () => {
  setIsFocus(true);
  if (inputRef.current) {
    inputRef.current.focus();
  }
}

<TouchableWithoutFeedback onPress={onPress}>
  <View>
    <TextInput
      {...props}
      ref={inputRef}
      onFocus={() => setIsFocus(true)}
      onBlur={() => setIsFocus(false)}
    />
  </View>
</TouchableWithoutFeedback>

The issue is when pressing on one InputField , it's focusing on the input but the cursor stays on the previous focused InputField .问题是按下一个InputField时,它专注于输入,但 cursor 停留在前一个聚焦的InputField上。 I know the .focus() function is working using console.log on the current focused input but the cursor itself does not move to the pressed element (meaning the keyboard does not appear on the correct input context).我知道.focus() function 在current聚焦输入上使用console.log工作,但 cursor 本身不会移动到按下的元素(这意味着键盘不会出现在正确的输入上下文中)。

What seems to be the issue in my code?我的代码中似乎有什么问题? or in general?还是一般?

NOTE: that I'm using this component for additional styling and animation.注意:我正在使用此组件进行额外的样式设置和 animation。

I reproduced your code on codesandbox HERE .我在 codesandbox HERE上复制了您的代码。 It seems there isn't a problem with your code itself.您的代码本身似乎没有问题。

For one thing, I think you can remove "isFocus" variable since you're not using it.一方面,我认为您可以删除“isFocus”变量,因为您没有使用它。 (OR remove the inputRef and just use the isFocus variable, which I think is better). (或者删除 inputRef 并只使用 isFocus 变量,我认为这样更好)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM