react如何生成组件
创建 React 组件的几种方法
函数组件
使用函数定义组件是最简单的方式,适用于无状态或使用 Hooks 的组件:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
箭头函数组件
ES6 箭头函数写法更简洁:
const Welcome = (props) => <h1>Hello, {props.name}</h1>;
类组件
通过继承 React.Component 实现,适用于需要生命周期和状态的复杂组件:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
组件使用与导出
默认导出
单个组件文件通常采用默认导出:
export default Welcome;
命名导出
支持导出多个组件:
export { Welcome, AnotherComponent };
组件嵌套与 Props
传递 Props
父组件通过属性传递数据:

<Welcome name="Alice" />
子组件渲染
通过 children 或自定义属性实现嵌套:
<Card>
<Welcome name="Bob" />
</Card>
状态管理
函数组件中使用 State
通过 useState Hook 管理状态:
const [count, setCount] = React.useState(0);
类组件中使用 State
在构造函数中初始化状态:

class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
}
生命周期与副作用
函数组件副作用
使用 useEffect 处理生命周期逻辑:
React.useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
类组件生命周期
通过特定方法如 componentDidMount 实现:
componentDidMount() {
console.log('Component mounted');
}
组件优化技巧
React.memo 优化
避免不必要的函数组件重渲染:
const MemoizedComponent = React.memo(MyComponent);
PureComponent 优化
类组件自动浅比较 Props 和 State:
class OptimizedComponent extends React.PureComponent {}





