儿童使用动态包装React



如果定义了,我想使用从道具传递的组件来包装子级。


interface ExampleProps {
wrapper: JSX.Element;
}
function Example({ wrapper }: ExampleProps) {
return (
// Wrap this with `wrapper`, only if it is defined, else don't wrap.
<Child></Child>
)
}

我们怎么能做到这一点?

你可以这样做

function Example({ wrapper }) {
if(wrapper) {
const Wrapper = wrapper //to make it alike component
return <Wrapper><Child></Child></Wrapper>
}
return (
<Child></Child>
)
}

尝试:

function Example({ wrapper, children }) {
const Wrapper = wrapper || React.Fragment; // custom components should start with capital letter
return (
<Wrapper>
{children}
</Wrapper>
)
}

最新更新