React 的 props 与它们的值同名 [英] React's props with the same name as their value

查看:50
本文介绍了React 的 props 与它们的值同名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以将 props 隐式传递给具有相同名称和值的组件吗?

示例:假设我有一个名为 x 的变量: const x = 1;我有一个组件,它有一个名为 x 的道具.我可以将这个变量作为值隐式传递吗?像这样:

?

解决方案

布尔值可以隐式传递给组件,正如@Ajay 在评论中也指出的,如

基本上等价于

然而,如果你的变量不是布尔值,那么你需要像这样写

或者如果你有很多这样的道具,你可以组成一个像

const cmpProps = {X,是,富,酒吧}

并使用像

这样的Spread属性传递它们

Can we pass props to a component that has the same name and value implicitly?

Example: Let's say that I have a variable called x: const x = 1; and I have a component that has a prop called x. Can I pass it this variable as value implicitly? like that: <div x/>?

解决方案

Booleans can be passed implicitly to the component as @Ajay also pointed out in comments, like

<div x />

which is basically equivalent to

<div x={true} />

However, if your variable is something other than a boolean, than you need to write it like

<div x={x} />

Or if you have a number of such props, you can form an object like

const cmpProps = {
   x,
   y,
   foo,
   bar
}

and pass them using Spread attributes like

<Comp {...cmpProps} />

这篇关于React 的 props 与它们的值同名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆