react如何使用props
使用 Props 的基本方法
在 React 中,props(属性)是父组件向子组件传递数据的主要方式。props 是只读的,子组件不能直接修改它们。
定义 props 父组件通过类似 HTML 属性的方式传递数据给子组件:
<ChildComponent name="John" age={25} />
接收 props
子组件通过函数参数或 this.props 接收:
// 函数组件
function ChildComponent(props) {
return <div>{props.name}, {props.age}</div>;
}
// 类组件
class ChildComponent extends React.Component {
render() {
return <div>{this.props.name}, {this.props.age}</div>;
}
}
Props 的默认值
可以为 props 设置默认值,当父组件没有传递时使用默认值。
函数组件
function ChildComponent({ name = 'Anonymous', age = 18 }) {
return <div>{name}, {age}</div>;
}
类组件
class ChildComponent extends React.Component {
static defaultProps = {
name: 'Anonymous',
age: 18
};
render() {
return <div>{this.props.name}, {this.props.age}</div>;
}
}
Props 的类型检查
使用 PropTypes 可以对 props 进行类型检查(React 15.5 之后需要单独安装 prop-types 包)。

import PropTypes from 'prop-types';
function ChildComponent(props) {
return <div>{props.name}, {props.age}</div>;
}
ChildComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number
};
传递复杂数据
可以传递对象、数组甚至函数作为 props。
传递对象
const person = { name: 'John', age: 25 };
<ChildComponent person={person} />
传递函数
function handleClick() {
console.log('Clicked');
}
<ChildComponent onClick={handleClick} />
使用展开运算符传递 Props
可以使用展开运算符批量传递 props。

const props = {
name: 'John',
age: 25,
occupation: 'Developer'
};
<ChildComponent {...props} />
在子组件中处理 Props
可以在子组件中对 props 进行处理后再使用。
function ChildComponent({ items }) {
const filteredItems = items.filter(item => item.active);
return (
<ul>
{filteredItems.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
组合组件与 children prop
可以使用特殊的 children prop 来传递子元素。
function ParentComponent() {
return (
<ChildComponent>
<p>This will be passed as children</p>
</ChildComponent>
);
}
function ChildComponent({ children }) {
return <div>{children}</div>;
}
高级 Props 模式
Render Props 一种使用 props 共享代码的技术。
<DataProvider render={data => (
<div>{data}</div>
)} />
Prop 代理 高阶组件可以通过 props 代理增强组件功能。
function withEnhancement(WrappedComponent) {
return function EnhancedComponent(props) {
const enhancedProps = { ...props, extra: 'value' };
return <WrappedComponent {...enhancedProps} />;
};
}






