将渲染属性传递给 React 组件中的子组件

huangapple go评论75阅读模式
英文:

Pass render props to children in a React complement

问题

我有一个名为Pagination的组件,我想将多个属性传递给组件的子元素,类似于Headless UI菜单项上的active属性:

<Menu.Item>
  {({ active }) => (
    <a className={`${active && 'bg-blue-500'}`} href="/account-settings">
      Account settings
    </a>
  )}
</Menu.Item>

我想传递一个activeItem属性和itemsCount属性,并允许用户以任何他们想要的方式渲染它。一个示例实现可能是:

<Pagination>
  {({ activeItem, itemsCount }) => (
    <span>{activeItem}</span>
    <span>{itemsCount}</span>
  )}
</Pagination>

Pagination的基线组件如下:

interface PaginationProps extends React.HTMLAttributes<HTMLDivElement> {
  children: React.ReactElement;
}

const Pagination = ({ children, ...rest }: PaginationProps) => {
  const { state } = useLightboxContext();
  return (
    <div {...rest}>
    </div>
  );
};

我该如何实现这个?

英文:

I have a component, called Pagination and I want to pass multiple props down to the children of the component, similar to active on the Menu item of Headless UI’s menu:

&lt;Menu.Item&gt;
  {({ active }) =&gt; (
    &lt;a className={`${active &amp;&amp; &#39;bg-blue-500&#39;}`} href=&quot;/account-settings&quot;&gt;
      Account settings
    &lt;/a&gt;
  )}
&lt;/Menu.Item&gt;

I want to pass an activeItem prop and itemsCount prop, and allow users to render it in whatever way they want to. An example implementation could be:

&lt;Pagination&gt;
  {({ activeItem, itemsCount }) =&gt; (
    &lt;span&gt;{ activeItem }&lt;/span&gt;
    &lt;span&gt;{ itemCount }&lt;/span&gt;
  )}
&lt;/Pagination&gt; 

And the baseline component for Pagination is:

interface PaginationProps extends React.HTMLAttributes&lt;HTMLDivElement&gt; {
  children: React.ReactElement;
}

const Pagination = ({ children, ...rest }: PaginationProps) =&gt; {
  const { state } = useLightboxContext();
  return (
    &lt;div {...rest}&gt;
    &lt;/div&gt;
  );
};

How can I do this?

答案1

得分: 1

如我在评论中提到的,这是实现的方式:

function Comp({ children }) {
  return children({ activeItem: 1, itemsCount: 2 });
}

function App() {
  return (
    &lt;Comp&gt;
      {({ activeItem, itemsCount }) =&gt; (
        &lt;p&gt;
          {activeItem}, {itemsCount}
        &lt;/p&gt;
      )}
    &lt;/Comp&gt;
  );
}

这将呈现出 1, 2

英文:

As I mentioned in a comment, here is the way to do it:

function Comp({ children }) {
  return children({ activeItem: 1, itemsCount: 2 });
}

function App() {
  return (
    &lt;Comp&gt;
      {({ activeItem, itemsCount }) =&gt; (
        &lt;p&gt;
          {activeItem}, {itemsCount}
        &lt;/p&gt;
      )}
    &lt;/Comp&gt;
  );
}

This will render 1, 2.

huangapple
  • 本文由 发表于 2023年2月16日 04:56:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465360.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定