FORMA

组件与 Props

React 应用由组件树组成。Props 是父组件传入子组件的只读参数;子组件通过回调 props 向父组件上报事件。见 JSXHooks

Props 与单向数据流

tsx
type ButtonProps = {
  label: string;
  disabled?: boolean;
  onPress: () => void;
};

function Button({ label, disabled = false, onPress }: ButtonProps) {
  return (
    <button type="button" disabled={disabled} onClick={onPress}>
      {label}
    </button>
  );
}
  • 不要修改 props;需要“子改父数据”时由父组件持有 state,通过 onPress 等回调更新。
  • 展开传递:<Profile {...user} /> 等价于逐个属性绑定。

受控与非受控组件

类型说明
受控表单值由 React state 驱动,如 value={text} onChange={e => setText(e.target.value)}
非受控值存在 DOM 中,用 ref 读取,如 <input ref={inputRef} defaultValue="..." />

复杂表单可配合 React Hook Form 等库。

组合模式

children

tsx
function Card({ children }: { children: React.ReactNode }) {
  return <section className="card">{children}</section>;
}

<Card>
  <h2>标题</h2>
  <p>内容</p>
</Card>;

插槽式 props

tsx
function Layout({
  header,
  footer,
  children,
}: {
  header?: React.ReactNode;
  footer?: React.ReactNode;
  children: React.ReactNode;
}) {
  return (
    <>
      {header}
      <main>{children}</main>
      {footer}
    </>
  );
}

复合组件(Compound Components)

父组件通过 Context 向子组件共享隐式状态(如 Tabs、Select),避免 props 层层传递。实现时常配合 Context

提升状态(Lifting State Up)

多个兄弟组件共享状态时,将 state 提升到最近共同父组件,再通过 props 下发。

与 Vue 对照(简表)

ReactVue
传参props 只读props 单向
双向绑定受控 + onChange 或库v-model
默认插槽children默认插槽
作用域插槽render props / 函数 childrenv-slot

参考文献

以下链接在编写时均可正常访问:

资料说明
React:组件首组件
React:Props传递 props
React:受控组件受控 input

Series

react

3 / 16