react-typescript prop 父子组件数据类型不对应
Data type does not correspnd between parent and child component in treact-typescript prop
我正在使用 React 和 TypeScript 构建一个应用程序
我正在使用 props 将我的数据传递给子组件
我在父组件中声明了属性的数据类型作为接口
传递给子组件
但我收到错误提示,它不对应
父组件
interface IProperty {
property: {
title: string;
}[];
}
const Dashboard = () => {
const [loading, setLoading] = useState(true);
const [properties, setProperties] = useState<IProperty["property"]>([
{
title: "New estate"
}
]);
return (
<div className="__recent-upload">
<ListOfProperties loading={loading} datas={properties} />
</div>
)
export default Dashboard
子组件
interface IProperty {
property: {
title: string;
}[];
}
const ListOfProperties: React.FC<{ loading: boolean, datas: IProperty }> = ({ loading, datas }) => {
return (
<div>
<h4 className="ml-4">Newly uploaded Properties</h4>
<Skeleton active loading={loading}>
<div className="table">
</div>
</Skeleton>
</div>
);
};
export default ListOfProperties;
错误
TS2741: Property 'property' is missing in type '{ title: string; }[]'
but required in type 'IProperty'.
您的错误是因为 data
需要一个带有 property
键的完整对象。但是你只发送一个数组[ {title: "foo" } ]
.
您有两种可能的解决方案:
1- 对 useState
使用相同的类型
const [properties, setProperties] = useState<IProperty>([{
property: {
title: "New estate"
}
}]);
2- 或将正确的对象绕过道具
<ListOfProperties loading={loading} datas={
{property:properties}
} />
我正在使用 React 和 TypeScript 构建一个应用程序
我正在使用 props 将我的数据传递给子组件
我在父组件中声明了属性的数据类型作为接口
传递给子组件
但我收到错误提示,它不对应
父组件
interface IProperty {
property: {
title: string;
}[];
}
const Dashboard = () => {
const [loading, setLoading] = useState(true);
const [properties, setProperties] = useState<IProperty["property"]>([
{
title: "New estate"
}
]);
return (
<div className="__recent-upload">
<ListOfProperties loading={loading} datas={properties} />
</div>
)
export default Dashboard
子组件
interface IProperty {
property: {
title: string;
}[];
}
const ListOfProperties: React.FC<{ loading: boolean, datas: IProperty }> = ({ loading, datas }) => {
return (
<div>
<h4 className="ml-4">Newly uploaded Properties</h4>
<Skeleton active loading={loading}>
<div className="table">
</div>
</Skeleton>
</div>
);
};
export default ListOfProperties;
错误
TS2741: Property 'property' is missing in type '{ title: string; }[]'
but required in type 'IProperty'.
您的错误是因为 data
需要一个带有 property
键的完整对象。但是你只发送一个数组[ {title: "foo" } ]
.
您有两种可能的解决方案: 1- 对 useState
使用相同的类型const [properties, setProperties] = useState<IProperty>([{
property: {
title: "New estate"
}
}]);
2- 或将正确的对象绕过道具
<ListOfProperties loading={loading} datas={
{property:properties}
} />