![](/img/trans.png)
[英]React Native: How to move to the next input filed after pressing the “next” keyboard button?
[英]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.