组件属性
分类 | Hooks | Classes |
---|---|---|
属性声明及默认值 | props=default-value | static defaultProps v0.13/ES2022 |
属性类型及校验 | TypeScript | static propTypes v0.13/ES2022 |
读取属性值 | props | this.props v0.13 |
大纲
- 属性
- 声明
- 默认值
- 类型及校验
- 读取
- 绑定
- 透传/传递
- Children 属性
- Render 属性
- 声明
属性声明
- 属性声明
- 属性默认值
- 属性类型及校验(必填)
- Hooks
- Classes
// React 15.4及以前
// import PropTypes from 'react';
// React v15.5 已弃用
// 已更改从 prop-types 导入
// import PropTypes from 'prop-types';
// TypeScript 支持
// 声明属性类型及校验(必填)
interface Props {
person?: string;
size: number;
}
// ES6 默认参数支持
// 声明属性默认值
export default function Avatar({ person, size = 100 }: Props) {
return (
<h1>Hooks</h1>
)
}
// 声明属性类型及校验(React 19 将移除)
// Avatar.propTypes = {
// person: PropTypes.string.isRequired,
// size: PropTypes.number
// }
// 声明属性默认值及校验(React 19 将移除)
// Avatar.defaultProps = {
// size: 100
// }
export default function Profile() {
return (
// 声明属性
<Avatar person="" size={50} />
)
}
// https://zh-hans.react.dev/learn/passing-props-to-a-component#specifying-a-default-value-for-a-prop
// https://zh-hans.react.dev/blog/2024/04/25/react-19-upgrade-guide#removed-proptypes-and-defaultprops
import { Component } from 'react';
// import PropTypes from 'prop-types';
// TypeScript 支持
// 声明属性类型及校验(必填)
interface Props {
person?: string;
size: number;
}
class Avatar extends Component {
// ES2022 支持
// 声明属性默认值及校验
static defaultProps: Props = {
size: 100
}
// ES2022 支持
// 声明属性类型
// static propTypes = {
// person: PropTypes.string.isRequired,
// size: PropTypes.number
// }
render() {
return <h1>Classes</h1>
}
}
// Avatar.propTypes = {
// person: PropTypes.string.isRequired,
// size: PropTypes.number
// }
// Avatar.defaultProps = {
// size: 100
// }
export default Avatar;
export default function Profile() {
return (
// 声明属性
<Avatar person="" size={50} />
)
}
// https://zh-hans.react.dev/reference/react/Component#static-proptypes
// https://zh-hans.react.dev/reference/react/Component#static-defaultprops