Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

javascript - Using dot notation with functional component

Official ReactJs documentation recommends to create components following the dot notation like the React-bootstrap library:

<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:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>
);

Or, you can exploit named exports:

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...