我如何判断一个道具是否在反应组件中传递

How do I tell if a prop was passed in a react component

我有一个 React 函数组件,这个函数需要一些 props。

我想知道组件是否传递了特定的 prop。

假设我有一个组件 Song,它包含 1 个道具 Genre。我想知道使用时的组件是否与流派道具一起使用。

示例:

<Song></Song>
<Song genre="Rap"></Song>

编辑:清晰度

您可以只检查描述的 undefined 值。

例如:

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

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

把这个放在你的函数组件中 return 语句

可以为任何道具切换流派,实际上任何 return 真、假、1 或 0

{props.genre != undefined && // if genre is not(!=) undefined, which happens when you dont pass the genre prop when using the component, it will run the code. the && means AND, which is true when the left operand is true and the right operand is true (the JSX returns true, i wont get into why)
 <Card.Subtitle>
   {props.genre}
 </Card.Subtitle>
}

编辑:试图增加一些清晰度

也许你必须创建从父 genre 接收 props 的功能组件,而 genre 的默认 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(即“全部”)组件中流派的默认道具。