简体   繁体   中英

React native typeScript and forwardRef in a functional component

I'm in react native app an I use typeScript too. I have a functional component:

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}
    ...  

I create some ref for different input before my render:

const firstNameRef = React.createRef<TextInput>();
    const lastNameRef = React.createRef<TextInput>();
    const birthDateRef = React.createRef<TextInput>();

and I use after this component in a class like that:

<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}
              />

But when I want to use onSubmitEditing for focus the next input, I have this error: 在此处输入图像描述

How can I resolve this issue? Thank You!

not 100% sure what the question is here, but

<StyledInput
  ref={ref}
  testID="TextInputID"
  placeholderTextColor={placeHolderColor}
  placeholder={placeHolder}
  ...

should work, then you need to pass the ref in when calling this input.

Like this:

const FancyButton = React.forwardRef</* type of ref*/HTMLButtonElement, /* component props */ComponentProps>((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>))

It will be correctly typed as

const FancyButton: React.ForwardRefExoticComponent<React.RefAttributes<HTMLButtonElement>>

(You don't need to use React.FunctionComponent when using forwardRef).

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}
    ... 
}) 

I faced a similar problem a few months ago. I solved it by doing:

   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>
          </>
        );
      },
    );

Hope this gives you an idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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