合成
了解如何在 Chakra UI 中组合组件。
as
属性
¥The as
Prop
用于更改 React 组件渲染的底层 HTML 元素。它提供了一种在保留组件功能的同时更改底层元素的直接方法。
¥Used to change the underlying HTML element that a React component renders. It provides a straightforward way to change the underlying element while retaining the component's functionality.
<Heading as="h3">Hello, world!</Heading>
TypeScript:使用 as
属性需要注意的是,传递给 as
属性的组件类型必须与组件的属性兼容。我们不会从 as
属性推断底层组件的属性。
¥TypeScript: The caveat with the as
prop is that the types of the component
passed to the as
prop must be compatible with the component's props. We do not
infer the underlying component's props from the as
prop.
asChild
属性
¥The asChild
Prop
用于将组件的功能组合到其子元素上。此方法受 Radix UI 启发,提供了最大的灵活性。
¥Used to compose a component's functionality onto its child element. This approach, inspired by Radix UI, offers maximum flexibility.
<Popover.Root>
<Popover.Trigger asChild>
<Button>Open</Button>
</Popover.Trigger>
</Popover.Root>
在此示例中,asChild
属性允许将 Button
用作弹出窗口的触发器。
¥In this example, the asChild
prop allows the Button
to be used as the
trigger for the popover.
最佳实践
¥Best Practices
为了避免使用 as
和 asChild
属性时常见的陷阱,可以考虑以下一些最佳实践:
¥To avoid common pitfalls when using the as
and asChild
props, there are a
few best practices to consider:
-
Forward Refs:确保底层组件正确转发传递给它的 ref。
-
扩展属性:确保底层组件能够传播传递给它的 props。
const MyComponent = React.forwardRef((props, ref) => {
return <Box ref={ref} {...props} />
})
// with `as` prop
<MyComponent as="button" />
// with `asChild` prop
<Button asChild>
<MyComponent> Click me </MyComponent>
</Button>