如何创建react组件
创建 React 组件的步骤
使用函数组件
函数组件是 React 中最简单的组件形式,使用 JavaScript 函数定义。
import React from 'react';
function MyComponent() {
return <div>Hello, World!</div>;
}
export default MyComponent;
函数组件可以通过箭头函数简化:
const MyComponent = () => {
return <div>Hello, World!</div>;
};
使用类组件
类组件是传统的 React 组件形式,适用于需要生命周期方法或状态管理的场景。
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
return <div>Hello, World!</div>;
}
}
export default MyComponent;
添加 Props
Props 用于向组件传递数据,可以在函数组件和类组件中使用。
// 函数组件
const Greeting = (props) => {
return <div>Hello, {props.name}!</div>;
};
// 类组件
class Greeting extends Component {
render() {
return <div>Hello, {this.props.name}!</div>;
}
}
使用 State
State 用于管理组件内部状态,函数组件使用 useState Hook,类组件使用 this.state。
// 函数组件
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
// 类组件
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
组件组合
组件可以嵌套使用,形成更复杂的 UI 结构。
const App = () => {
return (
<div>
<Greeting name="Alice" />
<Counter />
</div>
);
};
生命周期方法(类组件)
类组件可以使用生命周期方法,如 componentDidMount、componentDidUpdate 等。
class Example extends Component {
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate() {
console.log('Component updated');
}
render() {
return <div>Lifecycle Example</div>;
}
}
使用 Hooks(函数组件)
Hooks 允许函数组件使用状态和其他 React 特性。
import React, { useState, useEffect } from 'react';
const Timer = () => {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(prevSeconds => prevSeconds + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <div>Seconds: {seconds}</div>;
};
最佳实践
- 优先使用函数组件和 Hooks,除非需要类组件的特定功能。
- 组件命名使用 PascalCase(如
MyComponent)。 - 将组件拆分为更小的可复用单元。
- 使用 PropTypes 或 TypeScript 进行类型检查。







