Props(属性)是 React 中组件间传递数据的主要方式,具有只读性。父组件通过 props 将数据传递给子组件,子组件通过 this.props
(类组件)或函数参数(函数组件)接收。Props 可以是任意类型:字符串、数字、对象、数组甚至函数。
1. 基本 Props 传递
函数式组件
// 父组件
function ParentComponent() {
return <ChildComponent name="Alice" age={25} />;
}
// 子组件(函数式)
function ChildComponent(props) {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
</div>
);
}
类组件
class ChildComponent extends React.Component {
render() {
return (
<div>
<p>Name: {this.props.name}</p>
<p>Age: {this.props.age}</p>
</div>
);
}
}
2. 复杂数据类型传递
传递对象和数组
// 父组件
function ParentComponent() {
const user = {
id: 1,
profile: { avatar: 'url.jpg', bio: 'Developer' }
};
const items = ['React', 'Vue', 'Angular'];
return <ChildComponent user={user} items={items} />;
}
// 子组件
function ChildComponent({ user, items }) {
return (
<div>
<img src={user.profile.avatar} />
<ul>
{items.map(item => <li key={item}>{item}</li>)}
</ul>
</div>
);
}
3. Props 默认值和类型限制
PropTypes 属性校验
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class TodoItem extends Component {
constructor(props) {
super(props);
}
}
// 属性校验
TodoItem.propTypes = {
value: PropTypes.string,
itemDelete: PropTypes.func,
index: PropTypes.string.isRequired
};
// 设置默认值
TodoItem.defaultProps = {
test: 'hello world'
};
export default TodoItem;
4. 监听 Props 变化
import React from 'react';
export default class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
type: ''
};
}
render() {
return (
<div>
{`父组件传过来的值${this.state.type}`}
</div>
);
}
// 监听父组件传过来的props变化
static getDerivedStateFromProps(props, state) {
// 当父组件传过来的type和子组件的type不同时,更新子组件state
if (props.type !== state.type) {
return {
type: props.type
};
}
// 如果没有变化,返回null
return null;
}
}
5. Render Props 模式
Render Props 是一种特殊类型的 Props 使用方式,可以将父组件的状态传递给子组件。
// 定义带有 Render Props 的组件
function Container(props) {
return (
<div>{props.render()}</div>
);
}
function Children() {
return <div>Children</div>;
}
function App() {
return (
// 使用 Render Props
<Container render={Children} />
);
}
6. 父子组件传值
父组件
import { useState } from 'react';
import ChildComponent from './ChildComponent';
export default function ParentComponent() {
const [count, setCount] = useState(1);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>使用Props进行传值</h1>
<ChildComponent count={count} handleClick={handleClick} />
<ChildComponent count={count} handleClick={handleClick} />
</div>
);
}
子组件
export default function ChildComponent({ count, handleClick }) {
return (
<button onClick={handleClick}>
点了 {count} 次
</button>
);
}
7. Props 使用注意事项
- 只读性:组件不应修改 props,如果需要修改,应该在父组件中处理
- 传递方式:父组件通过属性传递,子组件通过 props 接收
- 数据类型:可以传递任何类型的数据,包括函数、对象、数组
- 默认值:使用
defaultProps
设置默认值,避免未传递时的 undefined - 类型校验:使用
propTypes
进行类型检查,提高代码健壮性