Skip to content

Props

基本使用

jsx
import { Component } from 'react'

class View extends Component {
  render() {
    const { name, sex, age } = this.props

    return (
      <div>
        <p>姓名:{name}</p>
        <p>性别:{sex}</p>
        <p>年龄:{age}</p>
      </div>
    )
  }
}
jsx
import { Component } from 'react'

class View extends Component {
  constructor(props) {
    super(props)
  }

  render() {
    const { name, sex, age } = this.props

    return (
      <div>
        <p>姓名:{name}</p>
        <p>性别:{sex}</p>
        <p>年龄:{age}</p>
      </div>
    )
  }
}

默认值 && 类型校验

jsx
import { Component } from 'react'
import PropTypes from 'prop-types'

class View extends Component {
  // props 类型检查
  static propTypes = {
    name: PropTypes.string.isRequired,
    sex: PropTypes.string,
    age: PropTypes.number,
  }

  // props 默认值
  static defaultProps = {
    sex: '男',
    age: 18,
  }

  render() {
    const { name, sex, age } = this.props

    return (
      <div>
        <p>姓名:{name}</p>
        <p>性别:{sex}</p>
        <p>年龄:{age}</p>
      </div>
    )
  }
}
jsx
import { Component } from 'react'

class View extends Component {
  constructor(props) {
    super(props)
  }

  render() {
    const { name, sex, age } = this.props

    return (
      <div>
        <p>姓名:{name}</p>
        <p>性别:{sex}</p>
        <p>年龄:{age}</p>
      </div>
    )
  }
}

View.propTypes = {
  name: PropTypes.string.isRequired,
  sex: PropTypes.string,
  age: PropTypes.number,
}

// 默认值
View.defaultProps = {
  sex: '男',
  age: 18,
}

props.children

类似于 Vue 中的 Slot 插槽

jsx
import Card from './Card'

class View extends Component {
  render() {
    return (
      <div>
        <Card title="Card 组件标题1">
          <p>这是插入的段落</p>
          <button>操作按钮</button>
        </Card>

        <Card title="Card 组件标题2">
          <ul>
            <li>列表项一</li>
            <li>列表项二</li>
          </ul>
        </Card>
      </div>
    )
  }
}
jsx
import { Component } from 'react'

class Card extends Component {
  render() {
    const { children, title } = this.props

    return (
      <div style={styles.card}>
        {/* props 属性(普通):title */}
        <h3 style={styles.title}>{title}</h3>
        <div style={styles.content}>
          {/* props 属性(插槽):children */}
          {children}
        </div>
      </div>
    )
  }
}

const styles = {
  card: {
    border: '1px solid #ccc',
    borderRadius: 8,
    padding: 16,
    width: 300,
    backgroundColor: '#f9f9f9',
  },
  title: {
    marginBottom: 12,
  },
  content: {
    fontSize: 14,
  },
}

export default Card

基于 MIT 许可发布