繁体   English   中英

反应 Typescript 子组件

[英]React Typescript subcomponent

我正在尝试使用以下样式的子组件制作 React 组件: https://react-bootstrap.github.io/components/cards/它应该在左侧呈现一个组件,在右侧呈现一个组件

<MyComponent>
   <MyComponent.Left>
      foo
   </MyComponent.Left>
   <MyComponent.Right>
      bar
   </MyComponent.Right>
</MyComponent>

我的基本策略是创建这样的东西:

function MyComponent(props:PropsWithChildren):JSX.Element{
var leftComponent = ???;
var rightComponent = ???;
return 
(<div>
   <div className="this-goes-on-the-right">leftComponent</div>
   <div className="this-goes-on-the-left">rightComponent</div>
</div>);
}

function MyComponent.Left = function MyComponentLeft(props:PropsWithChildren){
   return (<div>props.children</div>);
}
function MyComponent.Right = function MyComponentRight(props:PropsWithChildren){
   return (<div>props.children</div>);
}

但是我不知道如何确定传递给 MyComponent 的哪些子项是 MyComponent.Left,哪些是 MyComponent.Right。 我如何在 typescript 中执行此操作?

他们正在使用Object.assign来分配“子组件”。

const Card: BsPrefixRefForwardingComponent<'div', CardProps> = React.forwardRef<
  HTMLElement,
  CardProps
>(
  (
    {
      props
    },
    ref,
  ) => {
    return (
      <Component
        ...
      </Component>
    );
  },
);

Card.displayName = 'Card';
Card.propTypes = propTypes;
Card.defaultProps = defaultProps;

export default Object.assign(Card, {
  Img: CardImg,
  Title: CardTitle,
  Subtitle: CardSubtitle,
  Body: CardBody,
  Link: CardLink,
  Text: CardText,
  Header: CardHeader,
  Footer: CardFooter,
  ImgOverlay: CardImgOverlay,
});

来源

  1. 可能有多种方法可以达到您的目标。 最基本的可能是为组件设置一些名称并检查每个子组件的名称( react docs ),但我不推荐这样做。

  2. 相反,您应该正确设置MyComponent.LeftMyComponent.Right的样式,以便无论它们传递给MyComponent的子级的顺序如何,它们都以所需的方式显示。

勾勒出我的意思:

function MyComponent(props:PropsWithChildren):JSX.Element{
  return (
    <div>{props.children}</div>
  );
}

function MyComponent.Left = function MyComponentLeft(props:PropsWithChildren){
   return (<div className="this-goes-on-the-left">props.children</div>);
}
function MyComponent.Right = function MyComponentRight(props:PropsWithChildren){
   return (<div className="this-goes-on-the-right">props.children</div>);
}

嵌套组件样式的类的实现可以基于 flex-box 规则、浮动规则或任何适合您的用例的规则。

  1. 与您的示例略有不同但可能有用的另一种选择是将组件作为道具传递,而不是孩子喜欢:
function MyComponent(props:PropsWithChildren):JSX.Element{
  return (
    <div>
       <div className="this-goes-on-the-right">{props.right}</div>
       <div className="this-goes-on-the-left">{props.left}</div>
    </div>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM