react如何实现组件
实现 React 组件的核心方法
React 组件可以通过函数组件和类组件两种方式实现。以下是具体实现方法:
函数组件
函数组件是使用 JavaScript 函数定义的组件,接收 props 作为参数并返回 React 元素。这是 React 16.8 引入 Hooks 后的推荐方式。
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
// 使用箭头函数
const Greeting = (props) => <h1>Hello, {props.name}!</h1>;
类组件
类组件是继承 React.Component 的 ES6 类,必须包含 render() 方法。
class Greeting 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>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
类组件中使用状态
通过 this.state 和 this.setState() 管理状态:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
生命周期方法(类组件)
类组件可以通过生命周期方法处理不同阶段的逻辑:
class LifecycleDemo extends React.Component {
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate() {
console.log('Component updated');
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return <div>Lifecycle Demo</div>;
}
}
函数组件替代生命周期
使用 useEffect Hook 替代生命周期方法:
import { useEffect } from 'react';
function LifecycleDemo() {
useEffect(() => {
console.log('Component mounted or updated');
return () => console.log('Component will unmount');
}, []); // 空数组表示仅在挂载和卸载时执行
return <div>Lifecycle Demo</div>;
}
组件通信
父传子(Props)
父组件通过 props 向子组件传递数据:
function Parent() {
return <Child message="Hello from parent" />;
}
function Child(props) {
return <p>{props.message}</p>;
}
子传父(回调函数)
通过回调函数实现子组件向父组件传递数据:
function Parent() {
const handleChildClick = (data) => {
console.log('Data from child:', data);
};
return <Child onClick={handleChildClick} />;
}
function Child({ onClick }) {
return <button onClick={() => onClick('Child data')}>Click Me</button>;
}
组件组合
通过 children prop 实现组件组合:
function Card({ children }) {
return <div className="card">{children}</div>;
}
function App() {
return (
<Card>
<h1>Title</h1>
<p>Content</p>
</Card>
);
}
最佳实践
- 优先使用函数组件和 Hooks
- 保持组件小型化和单一职责
- 使用 PropTypes 或 TypeScript 进行类型检查
- 对复杂状态管理考虑使用 Context 或状态管理库(如 Redux)
- 使用 React.memo 优化性能:
const MemoizedComponent = React.memo(function MyComponent(props) {
/* 使用 props 渲染 */
});






