如何使用子组件实现React组件并调用它们?

时间:2018-03-07 11:53:23

标签: reactjs

如何实现具有类似react-bootstrap Modal

结构的React组件
<Modal show={this.state.show} onHide={this.handleClose}>
  <Modal.Header closeButton>
    <Modal.Title>Modal heading</Modal.Title>
  </Modal.Header>
  <Modal.Body>
    <h1>My Body</h1>
  </Modal.Body>
  <Modal.Footer>
    <Button onClick={this.handleClose}>Close</Button>
  </Modal.Footer>
</Modal>

我正在尝试这样的解决方案:

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 } from 'react'

export default class CardHeader extends Component {
  render() {
    return (
      <div>
        {this.props.text}
      </div>
    )
  }
}

并打电话给他们:

<Card>        
    <Card.Header text='Header'/>
    <Card.Body text='Body'/>
    <Card.Footer text='Footer'/>
</Card>

但没有用!

2 个答案:

答案 0 :(得分:3)

实际上,您正在做的只是呈现父组件的子项。

因此,如果您只是将Card组件更改为...

import React, { Component } from 'react'

class Card extends Component {

  render() {
    return (
      <div>
        {this.props.children}
      </div>
    )
  }
}

export default Card

然后它将渲染您传递给组件的任何内容。

要导出并能够使用Card.Header等,您可以创建新的const

const card = {
    Header: HeaderComponent,
    Body: BodyComponent,
    Footer: FooterComponent
};

export {
    card as Card
}

答案 1 :(得分:0)

更改您的组件以呈现其children

import React, { Component } from 'react'

export default class CardHeader extends Component {
  render() {
    return (
      <div>
        {this.props.children}
      </div>
    )
  }
}

将静态属性添加到Card

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>