[英]React passing a variable to component as a prop
If I have a component like <MyComponent isRed/>
, is there a way to replace the isRed
prop with a variable so that I can pass <MyComponent isBlue />
or <MyComponent isGreen />
conditionally with the same component?如果我有一个像<MyComponent isRed/>
这样的组件,有没有办法用变量替换isRed
道具,以便我可以使用相同的组件有条件地传递<MyComponent isBlue />
或<MyComponent isGreen />
MyComponent isGreen />?
If I did <MyComponent color={isColor}/>
I would still need to determine what color
is at MyComponent
如果我做了<MyComponent color={isColor}/>
我仍然需要确定MyComponent
的color
I know I can achieve what I'm looking for by making a switch and return <MyComponent isRed/>
, <MyComponent isBlue/>
and <MyComponent isGreen/>
depending on the case but that's a lot of redundant code so I was wondering if there's a way to do something like <MyComponent {isColor}/>
?我知道我可以通过切换并根据具体情况返回<MyComponent isRed/>
、 <MyComponent isBlue/>
和<MyComponent isGreen/>
MyComponent isGreen/> 来实现我想要的,但这是很多冗余代码,所以我想知道是否有办法做类似<MyComponent {isColor}/>
的事情吗?
Maybe you could give some more context about what it is you're trying to do?也许您可以提供更多有关您正在尝试做什么的背景信息?
As I'm not entirely sure what your question is about, but I will try my best to answer.因为我不完全确定你的问题是关于什么的,但我会尽力回答。
If you need to actually set the color of something:如果您需要实际设置某物的颜色:
Let's say you're trying to set a background color of some element.假设您正在尝试设置某个元素的背景颜色。 You can just pass a string to the component to use it there:您可以将一个字符串传递给组件以在其中使用它:
let color = "#FF0000";
<YourComponent color={color} />
Using this approach you could directly use this string with the color value and use it to modify the color of your component:使用这种方法,您可以直接将此字符串与颜色值一起使用,并使用它来修改组件的颜色:
const YourComponentReceivingTheColor = ({color}) => {
return <div style={{ backgroundColor: color }} />
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.