函数组件(Functional Components):
函数组件是使用函数定义的 React 组件。它们通常是最简单、最直接的方式来定义 UI 组件,并且只接受一个 props 对象作为参数,并返回一个 React 元素。
function MyComponent(props) {
return (
<div>
<h1>{props.title}</h1>
<p>{props.text}</p>
</div>
);
}
类组件(Class Components):
类组件是使用 ES6 类定义的 React 组件。它们通常可以处理动态数据和内部状态,并支持更多的生命周期方法和其他高级特性。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<h1>{this.props.title}</h1>
<p>{this.props.text}</p>
<button onClick={() => this.handleClick()}>
Clicked {this.state.count} times
</button>
</div>
);
}
}
高阶组件(Higher Order Components):
高阶组件是一种用于重用组件逻辑的高级技术。它是一个函数,它接受一个组件作为参数并返回一个新的组件。
function withLogging(WrappedComponent) {
return class extends React.Component {
componentDidMount() {
console.log('Component mounted!');
}
render() {
return <WrappedComponent {...this.props} />;
}
};
}
const MyComponentWithLogging = withLogging(MyComponent);
函数作为子组件(Function as Children):
函数作为子组件是一种让组件可以接受一个函数作为子元素的技术。它使得组件可以接受动态的渲染逻辑,以便更好地适应不同的用例场景。
function MyComponent(props) {
return (
<div>
{props.children('Hello, World!')}
</div>
);
}
<MyComponent>
{text => <p>{text}</p>}
</MyComponent>
5. Render Props:
Render Props 是一种通过将一个函数作为 prop 传递给组件来共享组件状态的技术。它使得组件可以更好地管理自己的状态,并将状态共享给其他组件。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return this.props.render(this.state.count, this.handleClick.bind(this));
}
}
<MyComponent
render={(count, handleClick) => (
<div>
<h1>Count: {count}</h1>
<button onClick={handleClick}>
4.React Hooks:
React Hooks 是 React 16.8 引入的一种新特性,它使得函数组件也能够拥有类组件中的内部状态和生命周期方法。它们可以让代码更简洁,更易于理解和维护。
import React, { useState, useEffect } from 'react';
function MyComponent(props) {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Component mounted!');
}, []);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>{props.title}</h1>
<p>{props.text}</p>
<button onClick={handleClick}>
Clicked {count} times
</button>
</div>
);
}
8.Suspense 和 Lazy Loading:
Suspense 和 Lazy Loading 是 React 16.6 引入的一种新特性,它使得应用程序可以更好地处理异步数据和代码分割。Suspense 允许组件在数据加载完成之前显示一个备用的 UI,而 Lazy Loading 允许组件在需要时才进行加载,从而提高应用程序的性能。
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent(props) {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
</div>
);
}
以上是 React 中定义组件的一些方式和一些高级用法。当选择组件定义方式时,应该考虑组件的用例和复杂度,选择最适合的方式来编写和维护您的组件。