如何理解react prop
React Props 的基本概念
Props(Properties 的缩写)是 React 中用于父组件向子组件传递数据的机制。它们是只读的,子组件不能直接修改接收到的 props。Props 可以是任意类型的数据,包括字符串、数字、对象、数组甚至函数。
Props 的作用
- 数据传递:父组件通过 props 将数据传递给子组件。
- 组件复用:通过不同的 props 配置,子组件可以动态渲染不同内容。
- 单向数据流:数据从父组件流向子组件,确保数据变更的可预测性。
使用 Props 的示例
// 父组件
function ParentComponent() {
const message = "Hello from Parent";
return <ChildComponent greeting={message} />;
}
// 子组件
function ChildComponent(props) {
return <h1>{props.greeting}</h1>;
}
Props 的解构赋值
为了提高代码可读性,可以在子组件中直接解构 props:

function ChildComponent({ greeting }) {
return <h1>{greeting}</h1>;
}
默认 Props
可以为 props 设置默认值,避免未传递时的错误:

function ChildComponent({ greeting = "Default Greeting" }) {
return <h1>{greeting}</h1>;
}
Props 的类型检查
使用 PropTypes(或 TypeScript)可以定义 props 的类型,增强代码健壮性:
import PropTypes from 'prop-types';
function ChildComponent({ greeting }) {
return <h1>{greeting}</h1>;
}
ChildComponent.propTypes = {
greeting: PropTypes.string.isRequired,
};
Props 与 State 的区别
- Props:外部传入,不可变(子组件不能修改)。
- State:组件内部管理,可变(通过
setState或useState更新)。
传递函数作为 Props
父组件可以通过 props 将函数传递给子组件,实现子组件触发父组件的逻辑:
function ParentComponent() {
const handleClick = () => console.log("Button clicked");
return <ChildComponent onClick={handleClick} />;
}
function ChildComponent({ onClick }) {
return <button onClick={onClick}>Click Me</button>;
}






