react如何使用props
使用 Props 的基本方法
在 React 中,props(属性)是父组件向子组件传递数据的主要方式。props 是只读的,子组件不能直接修改它们。
// 父组件传递 props
function ParentComponent() {
return <ChildComponent name="Alice" age={25} />;
}
// 子组件接收 props
function ChildComponent(props) {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
</div>
);
}
解构 Props
为了提高代码可读性,可以在子组件中直接解构 props:
function ChildComponent({ name, age }) {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
设置默认 Props
当父组件没有传递某些 props 时,可以设置默认值:

function ChildComponent({ name = 'Unknown', age = 0 }) {
// 使用解构赋值的默认值
}
// 或者使用 propTypes
ChildComponent.defaultProps = {
name: 'Unknown',
age: 0
};
传递复杂数据
Props 可以传递任何 JavaScript 值,包括对象、数组和函数:
function ParentComponent() {
const user = {
name: 'Bob',
hobbies: ['Reading', 'Swimming']
};
const handleClick = () => {
console.log('Button clicked');
};
return <ChildComponent user={user} onClick={handleClick} />;
}
function ChildComponent({ user, onClick }) {
return (
<div>
<p>Name: {user.name}</p>
<ul>
{user.hobbies.map((hobby, index) => (
<li key={index}>{hobby}</li>
))}
</ul>
<button onClick={onClick}>Click me</button>
</div>
);
}
Props 验证
使用 prop-types 库(React 15.5+)进行 props 类型检查:

import PropTypes from 'prop-types';
function ChildComponent({ name, age }) {
// 组件实现
}
ChildComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number
};
在类组件中使用 Props
类组件通过 this.props 访问 props:
class ChildComponent extends React.Component {
render() {
const { name, age } = this.props;
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
}
传递子元素(children)
特殊 prop children 允许组件嵌套内容:
function ParentComponent() {
return (
<ChildComponent>
<p>This will be passed as children</p>
</ChildComponent>
);
}
function ChildComponent({ children }) {
return <div>{children}</div>;
}
注意事项
- Props 是单向数据流,只能从父组件传递到子组件
- 子组件不能直接修改接收到的 props
- 对于需要子组件修改的数据,父组件应该传递回调函数
- 避免过度使用 props 深层传递,考虑使用 Context API 或状态管理工具






