next.js 在prop通过子对象时,如何将类型与它对齐

xwbd5t1u  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(89)

问题:当我使用下面的表达式时,IDE警告typescript语法错误。我认为typescript期望子节点被分配为ReactNode而不是Array<object>

----/page.tsx/----
...
<TopBar>{[
    {text:"career",href:"",class:"p-0 m-0"},
    {text:"contact",href:"",class:"p-0 m-0"},
    {text:"patient registry",href:"/patient_registry",class:"custom-outline p-1 rounded-2xl px-4 hover:bg-black hover:text-white"}
]}</TopBar>
...
----------------

----/TopBar.tsx/----
export default function TopBar({children}:Array<object>){//<-SYNTAX ERROR
    const menus:Array<ReactNode> = [];
    children.forEach((element:object,index:number)=>{
        menus.push(<Link key={index} className={element.class} href={element.href}>{element.text}</Link>);
    });
    return(
    <div className={"pl-4 pr-16 flex items-center h-16 w-screen justify-between border-b-gray-200 border-2 fixed bg-white z-10"}>
        <ImgBlock src={"/assets/svg/logo.png"} width={"7rem"} height={"4rem"}/>
        <div className={"flex gap-8 items-center"}>
            {menus}
        </div>
    </div>
    );
}
----------------

字符串
React.js在@ts-ignore上运行良好,但我不能忍受我的源代码中的红色下划线。告诉我解决这个问题的语法。

gg58donl

gg58donl1#

的解构语义:

const { children }: Array<object> = [];

字符串
相当于:

const props: Array<object> = [];

const { children } = props;
// or const children = props.children;


这个错误是有意义的,因为属性children并不真正存在于数组类型中,因为它们不是ReactProps对象。
要修复它,我们需要的只是用一个对象 Package 原始类型,并添加一个键,键名为children,并带有您所需的类型。

type TopBarProps = {
  children: object[],
}

// approach 1. using the destructure syntax
const TopBar = ({ children }: TopBarProps) => {
  useEffect(() => {
    children.forEach(() => {
      // no error
    });
  }, []);
}

// approach 2. using the accessor operator
const TopBar2 = (props: TopBarProps) => {
  const children = props.children;

  useEffect(() => {
    children.forEach(() => {
      // no error
    });
  }, []);
}

1rhkuytd

1rhkuytd2#

export default function TopBar({ children }: { children: Array<object> }) {

字符串

azpvetkf

azpvetkf3#

谢谢大家!我只是这样编辑我的代码:

interface ElementType {text:string,class:string,href:string}
export default function TopBar({children}:{children:Array<ElementType>}){
    const menus:Array<ReactNode> = [];
    children.forEach((element:ElementType,index:number)=>{
        menus.push(<Link key={index} className={element.class} href={element.href}>{element.text}</Link>);
    });
    return(
    <div className={"pl-4 pr-16 flex items-center h-16 w-screen justify-between border-b-gray-200 border-2 fixed bg-white z-10"}>
        <ImgBlock src={"/assets/svg/logo.png"} width={"7rem"} height={"4rem"}/>
        <div className={"flex gap-8 items-center"}>
            {menus}
        </div>
    </div>
    );
}

字符串

相关问题