React Props 传值示例

深入理解React父子组件之间的数据传递与通信机制

👨 父组件 (ParentComponent)

// 父组件 - ParentComponent.tsx
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

// 父组件函数定义
const ParentComponent: React.FC = () => {
  // 1. 使用 useState Hook 创建状态
  const [message, setMessage] = useState<string>('Hello from Parent!');
  const [childData, setChildData] = useState<string>('');

  // 2. 定义处理子组件数据的回调函数
  const handleChildMessage = (data: string) => {
    // 接收并更新来自子组件的数据
    setChildData(data);
  };

  // 3. 更新要传递给子组件的消息
  const updateMessage = () => {
    setMessage(`Updated at ${new Date().toLocaleTimeString()}`);
  };

  // 4. JSX 返回组件结构
  return (
    <div>
      <h2>父组件</h2>
      <p>传递给子组件: {message}</p>
      <p>从子组件接收: {childData || '等待数据...'}</p>
      <button onClick={updateMessage}>更新消息</button>

      {/* 5. 使用 props 传递数据和方法给子组件 */}
      <ChildComponent
        message={message}              // 传递字符串数据
        onSendMessage={handleChildMessage}  // 传递回调函数
      />
    </div>
  );
};

export default ParentComponent;

🧩 子组件 (ChildComponent)

// 子组件 - ChildComponent.tsx
import React, { useState } from 'react';

// 1. 定义子组件接收的 props 类型接口
interface ChildProps {
  message: string;                    // 从父组件接收的消息
  onSendMessage: (data: string) => void;  // 发送消息给父组件的函数
}

// 2. 子组件函数定义,接收 props 参数
const ChildComponent: React.FC<ChildProps> = ({ message, onSendMessage }) => {
  // 3. 子组件内部状态
  const [inputValue, setInputValue] = useState<string>('');

  // 4. 处理输入框变化
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  // 5. 向父组件发送数据
  const sendToParent = () => {
    if (inputValue.trim()) {
      // 调用父组件传递的函数,将数据发送给父组件
      onSendMessage(inputValue);
      setInputValue('');  // 清空输入框
    }
  };

  // 6. JSX 返回组件结构
  return (
    <div>
      <h3>子组件</h3>
      <p>从父组件接收: {message}</p>

      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder="输入要发送给父组件的数据"
      />
      <button onClick={sendToParent}>发送给父组件</button>
    </div>
  );
};

export default ChildComponent;

📚 核心知识点

React Props 传递机制要点:

  • 单向数据流:数据只能从父组件流向子组件,子组件不能直接修改props
  • Props 只读性:子组件必须将props视为只读,不应修改传入的props
  • 回调函数:通过props传递函数,实现子组件向父组件通信
  • Props 验证:使用TypeScript接口定义props类型,确保类型安全
  • 默认值:可以为props设置默认值,当父组件未传递时使用
  • 组件解耦:通过props传递数据和函数,保持组件间的独立性和可复用性