react实现组件方式
React 实现组件的常见方式
React 提供了多种实现组件的方式,以下是主要的几种方法:
函数组件 函数组件是使用 JavaScript 函数定义的组件,简洁明了,适合无状态或使用 Hooks 的场景:
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
类组件
类组件通过继承 React.Component 实现,支持生命周期方法和状态管理:
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
箭头函数组件 箭头函数语法可以更简洁地定义函数组件:
const Greeting = (props) => <h1>Hello, {props.name}</h1>;
高阶组件 (HOC) 高阶组件是一个函数,接收一个组件并返回一个新组件,用于复用逻辑:
function withLogging(WrappedComponent) {
return class extends React.Component {
componentDidMount() {
console.log('Component mounted');
}
render() {
return <WrappedComponent {...this.props} />;
}
};
}
Render Props 通过 prop 传递渲染逻辑,实现组件间的代码共享:
class MouseTracker extends React.Component {
state = { x: 0, y: 0 };
handleMouseMove = (event) => {
this.setState({ x: event.clientX, y: event.clientY });
};
render() {
return (
<div onMouseMove={this.handleMouseMove}>
{this.props.render(this.state)}
</div>
);
}
}
自定义 Hooks 封装可复用的状态逻辑,供多个组件使用:
function useCounter(initialValue) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
return { count, increment };
}
复合组件 通过组合多个组件实现复杂功能,如 Context API 提供者/消费者模式:
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
无渲染组件 只处理逻辑不渲染 UI 的组件,通过子组件或 render prop 输出结果:
function DataFetcher({ url, children }) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url).then(res => res.json()).then(setData);
}, [url]);
return children(data);
}
每种方式适用于不同场景,函数组件和 Hooks 是现代 React 开发的主流选择,而类组件在维护旧代码时仍会见到。高阶组件和 render props 适用于复杂逻辑复用,自定义 Hooks 提供了更灵活的逻辑共享方式。







