reactjs - 如何将函数从父组件传递给具有可分配类型的子组件
问题描述
我是 TypeScript 的新手,我想将我的函数传递onDogSelected
给子组件<Dogs />
。
当我尝试时,我收到了一些这样的错误消息:
Type '{ onDogSelected: (e: any) => void; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.Property 'onDogSelected' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.
我不知道这是什么意思。我试图弄清楚但仍然没有解决方案。
const HomePage: React.FC = () => {
const [dogSelected, setDogSelected] = useState("");
const onDogSelected = (e: any) => {
setDogSelected(e.target.value)
}
return (
<ApolloProvider client={client2}>
<Dogs onDogSelected={onDogSelected} />
{dogSelected && <span>{dogSelected}</span>}
</ApolloProvider>
);
};
export default HomePage;
解决方案
React.FC
已弃用,您应该使用React.FunctionComponent
.
React.FunctionComponent
是泛型类型。如果您不再期待,您应该将组件的道具传递给它。
所以Dogs
组件应该看起来像,
import { FunctionComponent } from "react";
const Dogs: FunctionComponent<DogsProps> = (props) => {
...
};
interface DogsProps {
onDogSelected(e: any): void;
}
您不必创建接口或类型,只需将其作为参数传递
const Dogs: FunctionComponent<{ onDogSelected(e: any): void; }> = (props) => {
推荐阅读
- php - PHP:无法使用管理员帐户登录
- wordpress - 这个链接是从哪里生成的?我想将此链接重定向到博客主页
- python - 在 Python 中使用 Firebase-Admin 解压 AuthError(例如 Dict)
- java - 在 docker 文件中下载打开的 java sdk
- ios - 谷歌登录 iOS 与服务器
- pyspark - Databricks PySpark Job 不断被取消
- elasticsearch - 将特定的 CPU 资源分配给 pod - kubernetes.io/limit-ranger: 'LimitRanger 插件集:容器弹性搜索的 cpu 请求'
- mp4 - 使用 H264 数据编码 fmp4 文件时如何填充 avcC 框?
- python-3.x - 如何在 python/pyglet 中正确使用 gluUnProject?
- javascript - 如何使用 JavaScript 检索对象属性值?