【发布时间】:2022-01-17 16:07:03
【问题描述】:
所以我对 NextJs 还很陌生,过去几天一直在努力完成这项工作。仔细检查了互联网,并没有发现有同样问题的人,所以我可能误解了 NextJs 的工作原理。
我的文件结构如下:
//index.js
export default function Home() {
return (
<div className={classnames(indexStyles.wrapper, "gap")}>
<div className={indexStyles.itemswrapper}>
<Item image={banner1} text="Trusted by our clients"
button="View project" href="/project1" />
<Item image={banner2} text="Effective design"
button="View project" href="/project 2" />
</div>
)
}
这是我的索引文件(主页),其中有多个作为组件的项目,因为我想在其中包含不同的内容。这是 item 组件的样子:
// Item.js
const Item = ( props, { href } ) => {
return (
<div className={classnames(itemStyles.wrapper, "wrap", "center")}>
<div className={itemStyles.thumbnail}>
<div className={itemStyles.image}>
<Image src={props.image} alt=""/>
</div>
</div>
<div className={itemStyles.cta_wrapper}>
<div className={itemStyles.title}>
<h2>{props.text}</h2>
</div>
<div className={itemStyles.knop}>
<Button href={{href}} ><a>{props.button}</a></Button>
</div>
</div>
</div>
)
}
这就是 Button 组件的样子:
// Button.js
const Button = ({ children, href }) => {
return (
<div className={buttonStyles.button}>
<Link href={{href}}><a>{children}</a></Link>
</div>
)
}
所以我的问题是,如何将 index.js 页面中的 href 作为道具传递给 Item 组件,以便 Button.js 中的 Link 中的 href 得到更改。据我发现它与下一个路由器有关。我希望我的问题很清楚,如果没有,请不要再询问进一步的解释。
附言。我将所有的导入都留在了这个问题的每个文件的顶部,以使所有内容更加清晰,但所有内容都已正确导入。
【问题讨论】:
-
您访问道具不正确。您传递给
Item的所有道具都将在props对象下可用(无论是否已解构)。Item组件签名可能看起来像const Item = (props),然后您将href传递为<Button href={props.href}>。然后在Button中,您将href再次传递为<Link href={href}>。
标签: reactjs next.js components href react-props