我有一个名为“Layout.tsx”的包装器组件,顾名思义,它是我所有其他页面的包装器,并且具有导航、页脚等内容。我已经在传递子级了,但我也想传递 props,因为我想将某些状态从其子组件之一移动到其内部引用的另一个组件中。
布局.tsx
import React from "react";
...
import Alert from "../global/Alert";
export default function Layout({ children }, props: any) {
...
return (
<main className={styles.main}>
...
<Alert isVisible={props.isVisible} message={props.message} />
...
<section className={styles.content} style={{ transform: `translateY(${(isOpenNav === "false") ? "0vh" : "-45vh"})` }} onClick={() => setIsOpenNav("false")}>
{children}
</section>
...
</main>
);
}
Alert.tsx(其他组件,非子组件)
import styles from "./styles/Alert.module.scss";
export default function Alert(props: any) {
return (
<main className={styles.main} style={{ display: props.isVisible ? "flex" : "none" }}>
{props.message.title}
</main>
);
}
ShopItem.tsx(子组件)
import React from "react";
...
import Layout from "./layout/Layout";
...
export default function ShopItem() {
...
const [isVisible, setIsVisible] = React.useState(false);
return (
<Layout isVisible={isVisible} message={{ title: "hello" }}>
...
</Layout>
);
};
我的想法是,每当用户按下 ShopItem.tsx 组件中的某个按钮时,我想激活 Alert.tsx 组件。但是,我不断收到此错误:
Type '{ children: Element; isVisible: boolean; message: { title: string; }; }' is not assignable to type 'IntrinsicAttributes & { children: any; }'.
Property 'isVisible' does not exist on type 'IntrinsicAttributes & { children: any; }'.ts(2322)
(property) isVisible: boolean
您看到的错误表明您尝试传递的对象与“布局”组件中的“props”道具的类型不兼容。您尝试传递具有 'isVisible' 和 'message' 属性的对象,但 'props' 属性应具有类型 'IntrinsicAttributes & {children:any; }'.
您必须在“Layout”组件中具体描述“props”道具的类型才能解决此问题。放置在“布局”组件上方的类型声明将实现此目的:
type LayoutProps = {
isVisible: boolean;
message: {
title: string;
};
};
function Layout({ children }: LayoutProps, props: any) {
// ...
}