我正在使用 StencilJS 创建一些 Web 组件。我创建了一个实用程序组件,因为我看到自己一次又一次地重用一些逻辑:
export type ConditionalRenderProps = {
condition: boolean;
};
const ConditionalRender = ({ condition, children }: React.PropsWithChildren<ConditionalRenderProps>) => {
return condition && children ? children : null;
};
但是,当我在 Stencil 组件中使用它时,子属性未定义:
Component({
tag: 'foo',
styleUrl: 'foo.css'
shadow: true,
})
export class Foo {
render() {
return (
<Host>
<ConditionalRender condition={true}>
<span>foo</span>
</ConditionalRender>
</Host>
);
}
}
有什么问题吗?为什么
children
未定义?
我认为你正在混合 React 和 Stencil,这不会那样工作。
您可以使用 Stencil 功能组件,主要区别在于子组件在第二个参数中传递:
import { FunctionalComponent } from '@stencil/core';
export type ConditionalRenderProps = {
condition: boolean;
};
export const ConditionalRender: FunctionalComponent<ConditionalRenderProps> = ({ condition }, children) => {
return condition && children ? children : null;
};