簡體   English   中英

如何在使用 redux-form 按下下一個鍵盤按鈕后使用 useRef 鈎子選擇下一個 TextInput

[英]How to use useRef hook to select next TextInput after pressing next keyboard button with redux-form

我知道我們可以使用 React 類方法輕松地做到這一點。因為我們有 this.ref。 但我不確定如何在功能組件中使用 useRef 鈎子來做到這一點。

使用此處編寫的技巧

這就是我試圖做到這一點的方式。

  ...

  const inputEl1 = useRef(null);
  const inputEl2 = useRef(null);
  return (
        <Field
            name="first_name"
            component={MyTextInput}
            placeholder="First name"
            ref={inputEl1}
            refField={inputEl1}
            onEnter={() => {
              inputEl2.current.focus();
            }}
          />
          />
          <Field
            name="last_name"
            placeholder="Last name"
            component={MyTextInput}
            ref={inputEl2}
            refField={inputEl2}
          />
)
...

所以我需要將 ref 從字段傳遞到 MyTextInput,在 nextKeyPress 上我想關注第二個輸入組件,即 inputEl2

// 我的文本輸入

...
render() {
    const {
      input: { value, onChange, onBlur },
      meta: { touched, error },
      keyboardType,
      placeholder,
      secureTextEntry,
      editable,
      selectTextOnFocus,
      style,
      selectable,
      customValue,
      underlineColorAndroid,
      autoFocus,
      maxLength,
      returnKeyType,
      onEnter,
      refField,
    } = this.props;
    const { passwordVisibility, undelineColor } = this.state;

    return (
      <View style={{ marginVertical: 8 }}>
        <TextInput
          style={[{
            height: 50,
            paddingLeft: 20,
            color: Colors.SECONDARY_COMMON,
          }, style]}
          onBlur={val => onBlur(val)}
          keyboardType={keyboardType}
          underlineColorAndroid={undelineColor}
          placeholder={placeholder}
          returnKeyType={returnKeyType || 'go'}
          value={customValue || value.toString()}
          onChangeText={onChange}
          maxLength={maxLength}
          onSubmitEditing={onEnter}
          ref={refField}
        />
)
}
const inputEl2 = useRef(null);
<TextInput
        name="first_name"           
        placeholder="First name"
        onSubmitEditing={() => inputEl2.current.focus()}
      />

<TextInput
        name="last_name"
        placeholder="Last name"
        ref={inputEl2}
      />

它對我有用

如果它是您嘗試獲取其 ref 的子組件,則需要將 prop 作為其他名稱而不是ref傳遞。

這種方法對我有用

對於鈎子,使用 Ref 來初始化 ref。

const passwordInput = useRef(null);

為自定義組件的 ref prop 使用不同的名稱,例如 inputRef。

<CustomInput
  inputRef={ passwordInput }
/>

子組件 - 將 ref 設置為自定義 ref 屬性。

const CustomInput = props => {
  const { inputRef } = props;
  
  return ( <TextInput
    { ...props }
    ref={ inputRef }
  /> );
};

如果孩子需要使用像<TextInput ref={refField}...中的 ref 這樣的道具,那么道具需要是一個 ref(而不是字符串):

<Field refField={inputEl2} ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM