Props 是 React 组件之间传递数据的方式,理解 Props 是掌握组件通信的基础。

示例 1: 基本 Props 传递

你好, 张三!

interface GreetingProps {
  name: string;
  message?: string;  // 可选,有默认值
}

function Greeting({ name, message = "欢迎" }: GreetingProps) {
  return <p>{message}, {name}!</p>;
}

<Greeting name="张三" message="你好" />

示例 2: 各种类型的 Props

string: Hello

number: 42

boolean: true

array: [React, Vue, Angular]

object: {"name":"config","value":100}

类型: Props 可以是字符串、数字、布尔值、数组、对象、函数等任意类型。

示例 3: Props 默认值

只传必需属性(使用默认值):

不同 variant:

不同 size:

禁用状态:

interface ButtonProps {
  label: string;                              // 必需
  variant?: "primary" | "secondary" | "danger"; // 可选
  size?: "small" | "medium" | "large";        // 可选
  disabled?: boolean;                         // 可选
}

function Button({
  label,
  variant = "primary",   // 默认值
  size = "medium",       // 默认值
  disabled = false,      // 默认值
}: ButtonProps) { ... }

示例 4: 展开运算符传递

逐个传递:

卡片标题

这是卡片的内容,使用展开运算符传递所有属性。

卡片底部信息

展开传递:

卡片标题

这是卡片的内容,使用展开运算符传递所有属性。

卡片底部信息

const cardData = {
  title: "卡片标题",
  content: "内容...",
  footer: "底部"
};

// 两种方式效果相同
<Card title={cardData.title} content={cardData.content} />
<Card {...cardData} />  // 展开运算符
注意: 展开运算符要谨慎使用,避免传递不需要的属性。

示例 5: Props 透传

// 继承原生 input 的所有属性
interface CustomInputProps extends ComponentProps<"input"> {
  label: string;
  error?: string;
}

function CustomInput({ label, error, ...inputProps }: CustomInputProps) {
  return (
    <div>
      <label>{label}</label>
      <input {...inputProps} />  {/* 透传所有 input 属性 */}
      {error && <p>{error}</p>}
    </div>
  );
}

// 可以使用所有原生 input 属性
<CustomInput
  label="邮箱"
  type="email"
  placeholder="..."
  disabled
  required
/>

示例 6: 回调函数 Props

0
interface CounterProps {
  value: number;
  onChange: (newValue: number) => void;
  onReset?: () => void;  // 可选回调
}

// 父组件
const [count, setCount] = useState(0);

<Counter
  value={count}
  onChange={(newValue) => setCount(newValue)}
  onReset={() => setCount(0)}
/>
模式: 通过回调函数,子组件可以通知父组件状态变化,实现"状态提升"。