首页 > 解决方案 > 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?

标签: reactjs

解决方案


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>
  );
};

Edit wizardly-ishizaka-5ulgf


推荐阅读