0

试图将 ref 传递给我的搜索组件但没有任何成功。这是我的组件:

interface SearchInputProps {
  placeholder: string;
  onSearch: () => any;
}
// type TextInputProps = React.HTMLProps<TextInput>;

export const SearchInput: React.FC<SearchInputProps> = forwardRef<TextInput, SearchInputProps>(
  ({ placeholder, onSearch }, ref) => {
    const [searchText, setSearchText] = useState("");

    return (
      <View style={{ flex: 1, flexDirection: "row" }}>
        <View style={{ flexDirection: "row", alignItems: "center", flex: 1, padding: 5 }}>
          <Ionicons name="search" color={Colors.white} size={23} />
          <TextInput
            autoFocus
            placeholder={placeholder}
            placeholderTextColor={Colors.lightGrey2}
            style={{ marginLeft: 10, fontSize: 16, color: Colors.weakGrey, flex: 1 }}
            blurOnSubmit={false}
            value={searchText}
            onChangeText={(text) => {
              setSearchText(text);
              onSearch();
            }}
          ></TextInput>
          {searchText.length ? (
            <Ionicons
              name="close-circle"
              color={Colors.lightGrey}
              size={22}
              onPress={() => setSearchText("")}
              style={{ marginLeft: 5 }}
            />
          ) : null}
        </View>
      </View>
    );
  }
);

创建参考:

const inputRef = useRef<TextInput>();

组件:

<SearchInput placeholder={"Search a user"} onSearch={() => setIsTyping(true)} ref={inputRef} />

我收到此错误:

输入'{占位符:字符串;onSearch: () => 无效;参考:可变参考对象;}' 不可分配给类型 'IntrinsicAttributes & SearchInputProps & { children?: ReactNode; }'。类型'IntrinsicAttributes & SearchInputProps & { children?: ReactNode; 上不存在属性'ref' }

4

1 回答 1

1
export const SearchInput: React.FC<SearchInputProps> = forwardRef<TextInput, SearchInputProps>(

问题是您添加了一个显式类型注释,SearchInput它覆盖了由forwardRef.

React.FC<SearchInputProps>意味着这个组件只能接受来自SearchInputProps. 它对ref. SearchInput变量的正确类型使用ForwardRefExoticComponent而不是FC. 这是:

React.ForwardRefExoticComponent<SearchInputProps & React.RefAttributes<TextInput>>

但我建议你让类型SearchInput被推断出来,而不是显式地注释它。只需从您的代码中删除: React.FC<SearchInputProps>,它就会起作用。

打字稿游乐场链接

于 2021-04-15T16:42:59.903 回答