react实现组件
React 组件实现方法
React 组件是构建用户界面的独立模块,分为函数组件和类组件两种形式。以下是常见的实现方式:
函数组件
函数组件是最简单的 React 组件形式,使用 JavaScript/TypeScript 函数定义:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
现代 React 开发推荐使用箭头函数和 ES6 语法:
const Welcome = ({ name }) => {
return <h1>Hello, {name}</h1>;
};
类组件
类组件通过继承 React.Component 实现,支持生命周期方法和状态管理:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
状态管理
函数组件使用 useState Hook 管理状态:

import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
类组件通过 this.state 和 this.setState 管理状态:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
生命周期方法
类组件可以使用完整的生命周期方法:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
函数组件使用 useEffect Hook 替代生命周期:

import { useState, useEffect } from 'react';
function Clock() {
const [date, setDate] = useState(new Date());
useEffect(() => {
const timerID = setInterval(() => tick(), 1000);
return () => clearInterval(timerID);
}, []);
function tick() {
setDate(new Date());
}
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}
组件通信
父组件通过 props 向子组件传递数据:
function Parent() {
return <Child message="Hello from parent" />;
}
function Child({ message }) {
return <p>{message}</p>;
}
子组件通过回调函数向父组件通信:
function Parent() {
const handleClick = (data) => {
console.log('Data from child:', data);
};
return <Child onClick={handleClick} />;
}
function Child({ onClick }) {
return (
<button onClick={() => onClick('Some data')}>
Click me
</button>
);
}
高阶组件
高阶组件(HOC)是接收组件并返回新组件的函数:
function withLogging(WrappedComponent) {
return function(props) {
console.log('Rendering:', WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}
const EnhancedComponent = withLogging(MyComponent);
自定义 Hook
自定义 Hook 可以提取组件逻辑:
function useCounter(initialValue) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return { count, increment, decrement };
}
function Counter() {
const { count, increment } = useCounter(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}






