在 TypeScript 中使用带有功能组件的点表示法 [英] Using dot notation with functional component in TypeScript
问题描述
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>
感谢这个问题,我知道我可以创建这个结构像在 javascript 中那样使用功能组件:
Thanks to this question, I know that I can create this structure using functional components just like that in javascript:
const Card = ({ children }) => <>{children}</>
const Body = () => <>Body</>
Card.Body = Body
export default Card
使用 TypeScript 我决定给它添加相应的类型:
Using TypeScript I decided to add the corresponding types to it:
const Card: React.FunctionComponent = ({ children }): JSX.Element => <>{children}</>
const Body: React.FunctionComponent = (): JSX.Element => <>Body</>
Card.Body = Body // <- Error: Property 'Body' does not exist on type 'FunctionComponent<{}>'
export default Card
问题是现在 TypeScript 不允许赋值 Card.Body = Body
并给我错误:
Problem is now that TypeScript don't allow the assignment Card.Body = Body
and give me the error:
FunctionComponent<{}>"类型上不存在属性Body"
Property 'Body' does not exist on type 'FunctionComponent<{}>'
那么我怎样才能正确输入这个代码才能使用这个代码结构?
So how can I type this correctly in order to use this code structure?
推荐答案
const Card: React.FunctionComponent & { Body: React.FunctionComponent } = ({ children }): JSX.Element => <>{children}</>
const Body: React.FunctionComponent = (): JSX.Element => <>Body</>
Card.Body = Body;
或更易读:
type BodyComponent = React.FunctionComponent;
type CardComponent = React.FunctionComponent & { Body: BodyComponent };
const Card: CardComponent = ({ children }): JSX.Element => <>{children}</>;
const Body: BodyComponent = (): JSX.Element => <>Body</>;
Card.Body = Body;
这篇关于在 TypeScript 中使用带有功能组件的点表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!