react如何定义一个组件
定义 React 组件的两种主要方式
函数组件
使用 JavaScript/TypeScript 函数定义,适用于无状态或使用 Hooks 的组件:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
箭头函数写法:
const Welcome = (props) => <h1>Hello, {props.name}</h1>;
类组件
通过继承 React.Component 实现,适用于需要生命周期方法的场景:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
组件使用规范
Props 类型检查
推荐使用 TypeScript 或 PropTypes 进行类型约束:
import PropTypes from 'prop-types';
function Welcome({ name }) {
return <h1>Hello, {name}</h1>;
}
Welcome.propTypes = {
name: PropTypes.string.isRequired
};
默认 Props 值
为可选属性设置默认值:
function Welcome({ name = 'Guest' }) {
return <h1>Hello, {name}</h1>;
}
现代 React 最佳实践
使用 Hooks
函数组件中通过 Hooks 管理状态和副作用:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
组件组合模式
通过 children 实现布局组件:
function Card({ children }) {
return <div className="card">{children}</div>;
}
// 使用
<Card><Welcome name="Alice" /></Card>






