我在 React Native 应用程序中,我也使用 typeScript。 我有一个功能组件:
const Input: React.FunctionComponent<IInputProps> = ({
inputStyle,
placeHolderColor = EAppColors.DARK_GREY,
placeHolder,
value,
onChangeText,
autoFocus,
onFocus,
onBlur,
onSubmitEditing,
ref,
keyboardType = EKeyboardType.DEFAULT,
}) => {
return (
<StyledInput
testID="TextInputID"
placeholderTextColor={placeHolderColor}
placeholder={placeHolder}
...
我在渲染之前为不同的输入创建了一些参考:
const firstNameRef = React.createRef<TextInput>();
const lastNameRef = React.createRef<TextInput>();
const birthDateRef = React.createRef<TextInput>();
我在这样的类中使用了这个组件:
<StyledTextInput
label={I18n.t('auth.heading.firstNameLabel')}
errorText={errorText}
ref={firstNameRef}
autoFocus={true}
placeHolder={I18n.t('auth.placeHolder.firstName')}
isFocused={focusOnFirstFields}
hasError={hasError}
onFocus={() => this.setState({ focusOnFirstFields: true })}
onBlur={() => this.setState({ focusOnFirstFields: false })}
showClearButton={showFirstClearButton}
value={firstName}
onClearText={() => this.onClearText(1)}
onChangeText={(value: string) =>
this.setState({
firstName: value,
disabled: false,
showFirstClearButton: true,
})
}
onSubmitEditing={() => {
if (lastNameRef !== null && lastNameRef.current !== null) {
lastNameRef.current.focus();
}
}}
keyboardType={EKeyboardType.DEFAULT}
/>
但是当我想使用 onSubmitEditing 聚焦下一个输入时,我有这个错误:
我该如何解决这个问题? 谢谢!
答案 0 :(得分:0)
不是 100% 确定这里的问题是什么,但是
<StyledInput
ref={ref}
testID="TextInputID"
placeholderTextColor={placeHolderColor}
placeholder={placeHolder}
...
应该可以,那么你需要在调用这个输入时传递 ref 。
答案 1 :(得分:0)
像这样:
const FancyButton = React.forwardRef</* type of ref*/HTMLButtonElement, /* component props */ComponentProps>((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>))
它会被正确输入
const FancyButton: React.ForwardRefExoticComponent<React.RefAttributes<HTMLButtonElement>>
(使用 forwardRef 时不需要使用 React.FunctionComponent
)。
const Input = React.forwardRef<TextInput, IInputProps>(({
inputStyle,
placeHolderColor = EAppColors.DARK_GREY,
placeHolder,
value,
onChangeText,
autoFocus,
onFocus,
onBlur,
onSubmitEditing,
keyboardType = EKeyboardType.DEFAULT,
}, ref /* <--- ref is passed here!!*/) => {
// assuming this is a TextInput
return (
<StyledInput
ref={ref}
testID="TextInputID"
placeholderTextColor={placeHolderColor}
placeholder={placeHolder}
...
})
答案 2 :(得分:0)
几个月前我遇到了类似的问题。我通过以下方式解决了:
import {TextInputProps, TextInput} from 'react-native';
type IProps = TextInputProps & {
labelText?: string;
};
const TextInputStd: React.FC<IProps> = React.forwardRef(
(
{
labelText,
...textInputProps
}: IProps,
ref: React.Ref<TextInput>,
) => {
const {styles} = useStyles(_styles);
return (
<>
<View style={[styles.textInputContainer, styles2.textInputContainer]}>
<Text style={styles.labelText}>{labelText || ''}</Text>
<View style={styles.inputWrapper}>
<TextInput style={styles.input} {...textInputProps} ref={ref} />
</View>
</View>
</>
);
},
);
希望这能给你一个想法。