Reactjs 如何使用子组件实现React组件并调用它们?
如何实现具有类似结构的React组件Reactjs 如何使用子组件实现React组件并调用它们?,reactjs,Reactjs,如何实现具有类似结构的React组件 模态标题 我的身体 接近 我正在研究一个类似这样的解决方案: import React, { Component } from 'react' import CardHeader from './CardHeader.jsx' import CardBody from './CardBody.jsx' import CardFooter from './CardFooter.jsx' class Card extends Component {
模态标题
我的身体
接近
我正在研究一个类似这样的解决方案:
import React, { Component } from 'react'
import CardHeader from './CardHeader.jsx'
import CardBody from './CardBody.jsx'
import CardFooter from './CardFooter.jsx'
class Card extends Component {
render() {
return (
<div>
{this.Header}
{this.Body}
{this.Footer}
</div>
)
}
}
Card.Header = CardHeader
Card.Body = CardBody
Card.Footer = CardFooter
export default Card
import React,{Component}来自“React”
从“./CardHeader.jsx”导入CardHeader
从“./CardBody.jsx”导入CardBody
从“./CardFooter.jsx”导入CardFooter
类卡扩展组件{
render(){
返回(
{this.Header}
{this.Body}
{this.Footer}
)
}
}
卡头=卡头
Card.Body=CardBody
Card.Footer=CardFooter
导出默认卡
子组件(全部相等)并接收要渲染的文本道具:
import React, { Component } from 'react'
export default class CardHeader extends Component {
render() {
return (
<div>
{this.props.text}
</div>
)
}
}
import React,{Component}来自“React”
导出默认类CardHeader扩展组件{
render(){
返回(
{this.props.text}
)
}
}
并称之为:
<Card>
<Card.Header text='Header'/>
<Card.Body text='Body'/>
<Card.Footer text='Footer'/>
</Card>
但是没用 实际上,您所做的只是渲染父组件的子组件 因此,如果您只是将
卡组件更改为
import React, { Component } from 'react'
class Card extends Component {
render() {
return (
<div>
{this.props.children}
</div>
)
}
}
export default Card
更改组件以渲染其子组件
import React, { Component } from 'react'
export default class CardHeader extends Component {
render() {
return (
<div>
{this.props.children}
</div>
)
}
}
像这样使用它:
<Card>
<Card.Header>Header</Card/Header>
<Card.Body>Body</Card.Body>
<Card.Footer>Footer</Card.Footer>
</Card>
标题
身体
页脚
什么不起作用?控制台中是否有错误?如果您在{this.props.text}
下添加一些文本,是否会显示该文本?您正在导入CardHeader
,但您的组件名为Header
,没有任何控制台。Card.jsx正确呈现,但是{this.Header}没有呈现。@Dan,我在CardHeader.jsx中将Header固定为CardHeader,但仍然相同:/{这个。道具。孩子们}?
import React, { Component } from 'react'
export default class CardHeader extends Component {
render() {
return (
<div>
{this.props.children}
</div>
)
}
}
import React, { Component } from 'react'
import CardHeader from './CardHeader.jsx'
import CardBody from './CardBody.jsx'
import CardFooter from './CardFooter.jsx'
class Card extends Component {
static Header = CardHeader;
static Body = CardBody;
static Footer = CardFooter;
render() {
return (
{ this.props.children }
)
}
}
export default Card;
<Card>
<Card.Header>Header</Card/Header>
<Card.Body>Body</Card.Body>
<Card.Footer>Footer</Card.Footer>
</Card>