问题描述
我们可以将 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 与它们的值同名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-26 23:24