reactjs - Pass order of an element as a property
问题描述
There is a code that looks like this:
<div>
<Foo order={1}/>
<Bar order={2}/>
...
<Foo order={10}/>
<div>
Multiple elements are located inside a div. Each of them needs to receive it's own position number. It would be a trivial task if these elements were recieved from the server and rendered dynamically via a map, but this is not the case. All these elements are actually predefined and written in a jsx file. I don't feel like passing the order
variable to every element is the best thing to do.
I know it is possible to get element's own position in the list of its parent's children using native js. Is there a react way to achieve this?
解决方案
You can make a wrapper component and inject order
prop for each of its children.
// Will inject order={index}
<GiveOrder>
<Foo />
<Bar />
<Foo />
</GiveOrder>
Using React.Children
API and React.cloneElement
:
const GiveOrder = ({ children }) => {
return React.Children.map(children, (child, index) =>
React.cloneElement(child, { order: index })
);
};
Full example:
const Foo = ({ order, title = "title" }) => {
return (
<>
<h3>{title}</h3>
<span>{order}</span>
</>
);
};
const GiveOrder = ({ children }) => {
return React.Children.map(children, (child, index) =>
React.cloneElement(child, { order: index })
);
};
const App = () => {
return (
<GiveOrder>
<Foo title="foo1" />
<Foo title="something" />
<Foo />
</GiveOrder>
);
};
推荐阅读
- python - /usr/bin/python3:没有名为 pytest 的模块
- twincat - 具有完全访问权限的 TwinCAT 3.1 fCoE 读写
- git - Docker 在 gitlab CI 中构建当前 git 分支
- hid - iOS 主页按钮的 HID 描述符 + 报告?
- mysql - 解决导入数据库上的特定 mysql 错误
- python - 如何在 SQLAlchemy 中使用 PostgreSQL 的 jsonb_to_record?
- java - 检查Java列表中是否有连续点大于阈值
- javascript - client.elements 不能从使用 nightwatch-api 的步骤定义中工作
- java - 如何从用于 addValueEventListener 的 for 循环内的查询中获取字符串值
- java - 在 Kubernetes 集群上运行时,Solace JMS 通道自行关闭(Spring Boot)