react组件实现
React 组件实现方法
React 组件是构建用户界面的基本单元,分为函数组件和类组件两种形式。以下介绍常见的实现方式:
函数组件 函数组件是使用 JavaScript 函数定义的组件,简洁高效:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
类组件 类组件通过 ES6 class 定义,包含生命周期方法:

class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Props 使用 组件通过 props 接收外部数据:
function Greeting(props) {
return <p>Welcome, {props.userName}</p>;
}
// 使用
<Greeting userName="Alice" />
State 管理 类组件中使用 state 管理内部状态:

class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<button onClick={this.increment}>
Count: {this.state.count}
</button>
);
}
}
Hooks 实现 函数组件中使用 useState 管理状态:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
组件组合 通过组合简单组件构建复杂 UI:
function App() {
return (
<div>
<Welcome name="Alice" />
<Welcome name="Bob" />
</div>
);
}
生命周期方法 类组件中可使用生命周期方法:
class Clock extends React.Component {
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({ date: new Date() });
}
render() {
return <div>Time: {this.state.date.toLocaleTimeString()}</div>;
}
}
最佳实践 保持组件小型化且功能单一 使用 PropTypes 进行类型检查 优先使用函数组件和 Hooks 合理拆分容器组件和展示组件






