React Props

props(properties 的缩写)是父组件传给子组件的参数,用来定制子组件显示的内容与行为。有了 props,同一个组件在不同地方可以"长得不一样",它是组件复用的桥梁。

向组件传递 props

使用组件时像给 HTML 标签写属性一样传值,子组件通过第一个参数接收:

function Welcome(props) {
  return <h1>你好,{props.name}</h1>
}

function App() {
  return (
    <div>
      <Welcome name="小明" />
      <Welcome name="小红" />
    </div>
  )
}

两个 Welcome 收到的 name 不同,分别显示"你好,小明"和"你好,小红"。

传值写法:引号还是花括号

字符串直接写在引号里,数字、变量、布尔值等都要放进花括号:

function User({ name, age, vip }) {
  return <p>{name}({age} 岁){vip ? '★VIP' : '普通用户'}</p>
}

<User name="小明" age={18} vip />

props 常配合解构语法直接取出字段,代码更简洁。

类组件读取 props

类组件通过 this.props 读取传入的属性:

import { Component } from 'react'

class Welcome extends Component {
  render() {
    return <h1>你好,{this.props.name}</h1>
  }
}

默认值 defaultProps

父组件没传某个 props 时,用 defaultProps 提供兜底值,避免界面出现 undefined:

function Button({ text }) {
  return <button>{text}</button>
}

Button.defaultProps = {
  text: '默认按钮'
}

未传 text 时按钮显示"默认按钮";类组件同样可以把 defaultProps 挂到类上。

props 是只读的:单向数据流

子组件不能修改自己的 props,只能读取;想让父组件数据变化,父组件会把"修改函数"也作为 props 传下来,由子组件调用:

import { useState } from 'react'

function Child({ count, onAdd }) {
  return <button onClick={onAdd}>当前 {count},点我增加</button>
}

function Parent() {
  const [count, setCount] = useState(0)
  return <Child count={count} onAdd={() => setCount(count + 1)} />
}

数据从父流向子、改动通过回调传回父级,这就是 React 的单向数据流。

小结:props 是组件的对外接口:父组件传值、子组件只读;字符串用引号、其它值用花括号,defaultProps 兜底、回调函数实现反向通信,这是组件间协作的最高频写法。

笔记加载中…