英文:
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:
<Menu.Item>
{({ active }) => (
<a className={`${active && 'bg-blue-500'}`} href="/account-settings">
Account settings
</a>
)}
</Menu.Item>
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:
<Pagination>
{({ activeItem, itemsCount }) => (
<span>{ activeItem }</span>
<span>{ itemCount }</span>
)}
</Pagination>
And the baseline component for Pagination is:
interface PaginationProps extends React.HTMLAttributes<HTMLDivElement> {
children: React.ReactElement;
}
const Pagination = ({ children, ...rest }: PaginationProps) => {
const { state } = useLightboxContext();
return (
<div {...rest}>
</div>
);
};
How can I do this?
答案1
得分: 1
如我在评论中提到的,这是实现的方式:
function Comp({ children }) {
return children({ activeItem: 1, itemsCount: 2 });
}
function App() {
return (
<Comp>
{({ activeItem, itemsCount }) => (
<p>
{activeItem}, {itemsCount}
</p>
)}
</Comp>
);
}
这将呈现出 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 (
<Comp>
{({ activeItem, itemsCount }) => (
<p>
{activeItem}, {itemsCount}
</p>
)}
</Comp>
);
}
This will render 1, 2
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论