我如何判断是否通过React组件中传递了道具

问题描述 投票:0回答:2
I具有一个React函数组件,此函数采用了一些prop。

我想知道该组件是否具有特定的道具。

,我有一个组件,歌曲,它具有1个道具,流派。我想知道是否与类型prop”使用时是否使用了组件。

示例:

网络未通过:

    <Song></Song>
GENRE通过:

    <Song genre="Rap"></Song>
  • Edit:Clarity
	

您可以检查描述的

undefined
javascript reactjs react-bootstrap
2个回答
0
投票
例如:

const MyComponent = ({ title, description }) => {
    return (
        <div class ="card">
            <div class="card-header">{title}</div>
            {description && <div class="card-body">{description}</div>}
        </div>
    )
}

在上面的示例中,我使用条件渲染来满足您的要求。

也许您必须创建从父proce接收道具的功能组合,而默认道具
genre

就是全部,也许该组件看起来像这样:


0
投票

如果我们设置了默认道具,那么当从父组件中发送props

const Song = ({ genre="all" }) => {
   if(genre === "all") {
     return(
        <div>this song list has a all genre</div>
     )
   } else if(genre === "Rap") {
     return(
        <div>this song list has a genre {genre}</div>
     )
   }
}
时,将应用
genre
(“所有”)组件中的默认道具。

您可以检查上述道具是否不确定。示例:

song

    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.