react进阶用法完全指南
React进阶用法可以涵盖许多不同的主题,例如高阶组件、错误边界、Suspense、React.memo、React.forwardRef等。以下是一些常见的进阶用法的简单示例:
- 高阶组件(Higher-Order Components, HOC):
import React from 'react';
const withSubscription = (WrappedComponent) => {
class WithSubscription extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
};
}
componentDidMount() {
// 订阅外部数据源
this.setState({
data: this.props.source.subscribe(data => this.setState({ data }))
});
}
componentWillUnmount() {
// 取消订阅
if (this.state.data) {
this.state.data.unsubscribe();
}
}
render() {
// 传递额外的props给被包装的组件
return <WrappedComponent {...this.props} {...this.state.data} />;
}
}
return WithSubscription;
};
export default withSubscription;
- 错误边界(Error Boundaries):
import React from 'react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
// 可以将错误信息上报给服务器
console.error('ErrorBoundary caught an error', error, info);
this.setState({ hasError: true });
}
render() {
if (this.state.hasError) {
// 可以渲染一个自定义的错误界面
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
- Suspense:
import React, { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
- React.memo:
import React from 'react';
const MemoizedComponent = React.memo((props) => {
// 如果props没有改变,将不会重新渲染
return <div>{props.data}</div>;
});
export default MemoizedComponent;
- React.forwardRef:
import React from 'react';
function MyComponent(props, ref) {
return <div ref={ref}>{props.text}</div>;
}
const ForwardedComponent = React.forwardRef((props, ref) => (
<MyComponent {...props} forwardedRef={ref} />
));
export default ForwardedComponent;
这些示例展示了React进阶用法的不同方面,但实际应用中可能需要根据具体场景选择合适的技术,并解决更复杂的问题。
评论已关闭