简体   繁体   English

使用带功能组件的点表示法

[英]Using dot notation with functional component

Official ReactJs documentation recommends to create components following the dot notation like the React-bootstrap library:官方 ReactJs 文档建议按照点符号创建组件,如React-bootstrap库:

<Card>
  <Card.Body>
    <Card.Title>Card Title</Card.Title>
    <Card.Text>
      Some quick example text to build on the card title and make up the bulk of
      the card's content.
    </Card.Text>
  </Card.Body>
</Card>

It is very easy to create this structure with the help of a class component:借助类组件很容易创建此结构:

const CardBody = ({ children }) => <div className='body'>{children}</div>;

class Card extends Component {
  static Body = CardBody;

  render() {
    return (
      <div className='card'>{this.props.children}</div>
    );
  }
}

But it's also recommended to use as much as possible functional component.但也建议尽可能多地使用功能组件。 Unfortunately I don't know how to achieve this using only functional component.不幸的是,我不知道如何仅使用功能组件来实现这一点。

If I follow this way , I'm no more able to use Card as a component because he is now an object of components:如果我按照这种方式,我就不能再使用Card作为组件,因为他现在是组件的对象:

const Card = {
  Component: CardComponent,
  Body: CardBody
}

export default Card

I'd have to use it that way, and it's not really what I want:我必须那样使用它,这不是我真正想要的:

<Card.Component>
  <Card.Body>
  ...

Do you have any idea how to do that?你知道怎么做吗?

In function component you can do like so:在功能组件中,您可以这样做:

// Card.react.js
const Card = ({ children }) => <>{children}</>;
const Body = () => <>Body</>;

Card.Body = Body;

export default Card;

// Usage
import Card from "./Card.react.js";

const App = () => (
  <Card>
    <Card.Body />
  </Card>
);

You can simply do -你可以简单地做 -

const CardBody = ({ children }) => <div className='body'>{children}</div>;

const Card = (props) => (
  <div className='card'>{props.children}</div>
);
Card.Body = CardBody

And then use it like然后像这样使用它

<Card>
  <Card.Body>
   ....

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

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