[英]cannot forward ref to component TypeScript error
试图将 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' }
export const SearchInput: React.FC<SearchInputProps> = forwardRef<TextInput, SearchInputProps>(
问题是您已经向forwardRef
SearchInput
的类型。
React.FC<SearchInputProps>
意味着这个组件只能接受来自SearchInputProps
的 props。 它对ref
一无所知。 SearchInput
变量的正确类型使用ForwardRefExoticComponent
而不是FC
。 这是:
React.ForwardRefExoticComponent<SearchInputProps & React.RefAttributes<TextInput>>
但我建议您让SearchInput
的类型被推断出来,而不是显式地注释它。 只需从您的代码中删除: React.FC<SearchInputProps>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.