首页 > 解决方案 > 关注动态生成的自定义输入

问题描述

我正在实现一个自定义 SMS 代码验证,它将显示未定义数量的输入:

在此处输入图像描述

我想管理这些输入的焦点,但我不知道如何。

实际上,我有这样的自定义文本输入:

export function ConfirmationCodeInput(props) {
return (
    <TextInput
        style={styles.confirmationCodeInput}
        keyboardType={"number-pad"}
        maxLength={1}
        ref={props.innerRef}
        secureTextEntry={true}
        selectionColor={'transparent'}
        returnKeyType={"next"}
        onChangeText={(event) => props.onTextChange(event)}
    />
)

还有我的父组件:

export function ConfirmationCode(props) {
let refs = [];
const [codeValue, setCodeValue] = useState(null);

function focusNextField(key) {
    //What to do here ?
}

function createInputs(): Array<any> {
    let inputs = [];
    for (let i = 0; i < props.codeLength; i++) {
        const ref = React.createRef();
        refs[i] = ref;
        const input = <ConfirmationCodeInput key={i}
                                             innerRef = {ref}
                                             onTextChange ={focusNextField}
        />;
        inputs.push(input);
    }

    return inputs;
}

return (
    <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
        {createInputs()}
    </View>
)

如何管理?

标签: reactjsreact-native

解决方案


更好的方法是定义一个您关注的隐藏输入,然后使用该输入的值显示在您的其他输入中。

export function ConfirmationCode(props) {
  const [codeValue, setCodeValue] = useState(null);


  function createInputs(): Array<any> {
      let inputs = [];
      for (let i = 0; i < props.codeLength; i++) {
          const input = <ConfirmationCodeInput key={i}
                                               value={codeValue[i] ? codeValue[i] : ''}
          />;
          inputs.push(input);
      }

      return inputs;
  }

  return (
      <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
        <TextInput
            keyboardType="numeric"
            style={{ width: 1, height: 1, opacity: 0 }}
            maxLength={6}
            caretHidden={true}
            autoFocus
            onChangeText={text => setCodeValue(text)}
         />
        {createInputs()}
      </View>
  )

像这样的东西。


推荐阅读