react如何实现组件
React 组件实现方法
React 组件可以通过函数组件和类组件两种方式实现,以下是具体方法和示例:
函数组件实现
函数组件是 React 中最简单的组件形式,通过 JavaScript 函数定义:
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
函数组件可以使用 Hooks 来管理状态和生命周期:
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>
);
}
类组件实现
类组件通过 ES6 的 class 语法定义,继承 React.Component:
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
类组件可以管理状态和使用生命周期方法:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
组件组合
组件可以嵌套组合使用:
function App() {
return (
<div>
<Greeting name="Alice" />
<Counter />
</div>
);
}
组件间通信
父组件通过 props 向子组件传递数据:
function Parent() {
const [value, setValue] = useState('');
return (
<div>
<Child value={value} onChange={setValue} />
</div>
);
}
function Child({ value, onChange }) {
return <input value={value} onChange={e => onChange(e.target.value)} />;
}
高阶组件
高阶组件(HOC)是接收组件并返回新组件的函数:
function withLogging(WrappedComponent) {
return function(props) {
console.log('Rendering:', WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}
const EnhancedComponent = withLogging(MyComponent);
自定义 Hooks
自定义 Hook 可以复用组件逻辑:

function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
return { count, increment };
}
function MyComponent() {
const { count, increment } = useCounter();
return <button onClick={increment}>Clicked {count} times</button>;
}






