[英]Can you pass props to a JSX reference?
Before I begin with my question, allow me to clarify - the question here is a simplification of the issue, I'm working on an already large codebase on a legacy project for a client on short timespan and re-structuring the data would take me more time than trying to figure this out - I know this is not an ideal way to be try to be passing props around, so please don't just link to tutorial about how to be passing props在我开始我的问题之前,请允许我澄清一下——这里的问题是对问题的简化,我正在为一个客户在很短的时间内为一个遗留项目开发一个已经很大的代码库,并且重新构建数据需要我比试图弄清楚这一点更多的时间 - 我知道这不是尝试传递道具的理想方式,所以请不要只链接到关于如何传递道具的教程
The gist of it is, I have a large array of objects, all of which have the following property { icon: <SomeJSXReference /> }
它的要点是,我有一大堆对象,所有这些对象都具有以下属性
{ icon: <SomeJSXReference /> }
I basically created a re-usable abstraction component that returns the icon property based on certain passed props into it.我基本上创建了一个可重用的抽象组件,它根据某些传递的道具返回图标属性。
Issue is, i need to pass one of the props to the icon
reference itself.问题是,我需要将其中一个道具传递给
icon
引用本身。 Here's a rough pseudo-component I've written, to make it a bit clearer.这是我写的一个粗略的伪组件,让它更清楚一点。
const objectsArray = [{ icon: <SpecificIcon /> }, /*...*/]
const Simplified = (props: { color: string }) => {
const { color } = props
const toRender = objectsArray.someOperationsLeadingToFinalObjectReference()
return toRender.icon
}
What I need to do is somehow append a stroke={color}
prop to the JSX referenced inside the toRender.icon
pointer我需要做的是以某种方式 append a
stroke={color}
道具到toRender.icon
指针内引用的 JSX
Resulting basically in结果基本上在
<toRender.icon stroke={color} />
(toRender as pseudo-pointer, note the lowercase) <toRender.icon stroke={color} />
(toRender 为伪指针,注意小写)<SpecificIcon stroke={color} />
(equivalent of above = what should be returned) ˆ <SpecificIcon stroke={color} />
(相当于上面的=应该返回的) ^ Note: This does not explicitly have to be <SpecificIcon />
, but rather whatever JSX.Element toRender.icon
points to注意:这不一定是
<SpecificIcon />
,而是 JSX.Element toRender.icon
指向的任何东西
Is there any way I could do this, that's not occuring to me?有什么办法可以做到这一点,我没有想到吗?
There are two ways you can do it.有两种方法可以做到。
{ icon: <SpecificIcon /> }
You can use React.cloneElement
:您可以使用
React.cloneElement
:
[<Counter />].map(Component => React.cloneElement(Component, { num: 5 }))
{ icon: SpecificIcon }
You can render it while passing props:您可以在传递道具时渲染它:
[Counter].map((Component, index) => <Component key={index} num={2} />)
See full example:查看完整示例:
const Counter = ({ num = 0 }) => <div>{num}</div>;
const App = () => {
return (
<>
<Counter />
{[<Counter />].map(Component =>
React.cloneElement(Component, { num: 4 })
)}
{[Counter].map((Component, index) => (
<Counter key={index} num={2} />
))}
</>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.