尝试将 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} />
我收到此错误:
Type '{ placeholder: string; onSearch: () => void; ref: MutableRefObject; }' is not assignable to type 'IntrinsicAttributes & SearchInputProps & { children?: ReactNode; }'. Property 'ref' does not exist on type 'IntrinsicAttributes & SearchInputProps & { children?: ReactNode; }
最佳答案
export const SearchInput: React.FC<SearchInputProps> = forwardRef<TextInput, SearchInputProps>(
问题是您已将显式类型注释添加到 SearchInput
它覆盖 forwardRef
创建的类型.
React.FC<SearchInputProps>
意味着该组件只能接受来自 SearchInputProps
的 props 。它对ref
一无所知。 SearchInput
的正确类型变量使用ForwardRefExoticComponent
而不是FC
。它是:
React.ForwardRefExoticComponent<SearchInputProps & React.RefAttributes<TextInput>>
但我建议您让 SearchInput
的类型被推断而不是明确地注释它。只需删除 : React.FC<SearchInputProps>
从你的代码中,它会起作用。
关于reactjs - 无法将引用转发到组件 TypeScript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66892649/