[英]How to pass props down to child component in React
So in my main component, I send props to a child component like this:因此,在我的主组件中,我将道具发送到这样的子组件:
<div className={styles.navBar}>
<MasterNavBar color={false} scrollChange={true} />
</div>
MasterNavBar gets access to the props correctly, but I need MasterNavBar to pass those props to a child component called NavBar, which I currently do like this: MasterNavBar 可以正确访问道具,但我需要 MasterNavBar 将这些道具传递给名为 NavBar 的子组件,我目前这样做:
<NavBar props />
However, when I do this, the props are not accessible in my NavBar component file.但是,当我这样做时,无法在我的 NavBar 组件文件中访问这些道具。 For example, in NavBar, doing props.color to get my color prop returns undefined.
例如,在 NavBar 中,执行 props.color 来获取我的颜色 prop 返回未定义。 So, am I passing my props incorrectly, or am I missing something else?
那么,我是错误地传递了我的道具,还是我错过了其他东西?
That's depend on which props NavBar is expecting.这取决于 NavBar 期望的道具。 If you don't care about typing (either with typescript or react PropTypes) you can simply do like this:
如果您不关心打字(使用 typescript 或反应 PropTypes),您可以简单地这样做:
<NavBar {...props} />
As Antonio Pantano said, you can pass the whole props to the <NavBar {...props}/>
component, but this is a bad practice way.正如Antonio Pantano所说,您可以将整个道具传递给
<NavBar {...props}/>
组件,但这是一种不好的做法。 This article explained why it is a bad practice way. 本文解释了为什么这是一种不好的做法。 So you can pass the
MasterNavBar
props to its child in these two ways:因此,您可以通过以下两种方式将
MasterNavBar
道具传递给它的孩子:
const MasterNavBar = (props) => {
/*
rest of your code
*/
return <NavBar color={props.color} scrollChange={props.scrollChange}/>
}
or或者
const MasterNavBar = ({color, scrollChange}) => {
/*
rest of your code
*/
return <NavBar color={color} scrollChange={scrollChange}/>
}
You can change the name of NavBar
props as you wish, and you access them in the NavBar
component by these names.您可以根据需要更改
NavBar
道具的名称,并通过这些名称在NavBar
组件中访问它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.