react 组件实现
React 组件实现方式
React 组件是构建用户界面的核心单元,主要分为函数组件和类组件两种形式。以下是具体实现方法:
函数组件实现
函数组件是使用 JavaScript 函数定义的组件,简洁且易于理解:
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
箭头函数写法:
const Greeting = (props) => <h1>Hello, {props.name}</h1>;
类组件实现
类组件通过 ES6 的 class 定义,可以包含状态和生命周期方法:
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
组件状态管理
函数组件中使用 Hooks 管理状态:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
类组件中使用 state 对象:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Clicked {this.state.count} times
</button>
);
}
}
组件生命周期
类组件中可以使用的生命周期方法示例:

class Example extends React.Component {
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate() {
console.log('Component updated');
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return <div>Lifecycle Example</div>;
}
}
函数组件中使用 useEffect 替代生命周期:
import { useEffect } from 'react';
function Example() {
useEffect(() => {
console.log('Component mounted');
return () => console.log('Component will unmount');
}, []);
return <div>Lifecycle Example</div>;
}
组件间通信
父组件向子组件传递 props:
function Parent() {
return <Child message="Hello from parent" />;
}
function Child(props) {
return <p>{props.message}</p>;
}
子组件向父组件传递数据:
function Parent() {
const handleData = (data) => {
console.log('Received:', data);
};
return <Child onSendData={handleData} />;
}
function Child({ onSendData }) {
return <button onClick={() => onSendData('Child data')}>Send</button>;
}
组件样式处理
内联样式:

function StyledComponent() {
return <div style={{ color: 'red', fontSize: 20 }}>Styled Text</div>;
}
CSS Modules:
import styles from './Component.module.css';
function StyledComponent() {
return <div className={styles.container}>Styled Text</div>;
}
Styled Components:
import styled from 'styled-components';
const StyledDiv = styled.div`
color: red;
font-size: 20px;
`;
function StyledComponent() {
return <StyledDiv>Styled Text</StyledDiv>;
}
高阶组件实现
高阶组件(HOC)是用于组件逻辑复用的高级技术:
function withLogging(WrappedComponent) {
return function(props) {
console.log('Rendering:', WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}
const EnhancedComponent = withLogging(MyComponent);
自定义 Hook 实现
自定义 Hook 可以提取组件逻辑以便复用:
function useCounter(initialValue = 0) {
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();
return <button onClick={increment}>{count}</button>;
}






