对功能组件使用点符号 [英] Using dot notation with functional component
问题描述
ReactJs官方文档建议按照 React-bootstrap 库:
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.
如果我遵循以此方式,则我'不再能够使用 Card
作为组件,因为他现在是组件的对象:
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>
...
您是否知道该怎么做?
推荐答案
在功能组件中,您可以这样做:
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>
);
这篇关于对功能组件使用点符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!