企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] # 框架 ## forwardRef, useImperativeHandle ~~~ import React, { useState, forwardRef, useImperativeHandle } from 'react'; import CustomModal from 'components/custom-modal/index'; function DistributionShareCard ({}, ref) { const [show, setShow] = useState(false); // 向外暴露show方法 useImperativeHandle(ref, () => ({ show: () => { setShow(true); } })); return ( <CustomModal show={show}></CustomModal> ) } export default forwardRef(DistributionShareCard) ~~~ ## createPortal ~~~ import { createPortal } from 'react-dom'; const portalHigh = typeof document != 'undefined' && document.querySelector('.portal-high'); { portalHigh ? createPortal( <React.Fragment> { <DynamicShareCard fandomName={this.state.title} isDistribution={this.isDistribution} money={this.props.payFandomInfo.shareUserMoney} liveId={this.liveId} userId={this.userId} ref={c => this.dynamicShareCardRef = c} /> } </React.Fragment> , portalHigh ):null } ~~~ ## 修饰器、ErrorBoundary ~~~ import React from 'react'; import PropTypes from 'prop-types'; import { EmptyContent } from '../qlchat-ui'; /** * 错误边界 目前没有hook对应的解决方案,先用class顶替 * 捕获组件渲染错误 * <ErrorBoundary> * { children } * </ErrorBoundary> */ class ErrorBoundary extends React.PureComponent { state = { hasError: undefined } get isPageComponent () { return this.props.page; } static getDerivedStateFromError (error) { return { hasError: error } } componentDidCatch (error, info) { console.log('ErrorBoundary: ', error.message, info.componentStack); if (!this.isPageComponent) { alert('功能故障,请稍候再试'); } if (typeof Tracker !== 'undefined') { try { // 上报错误 } catch (err) { } } } render () { if (this.state.hasError) { if (this.isPageComponent) { return <EmptyContent message="抱歉,该页面出现了一些问题,请稍后刷新重试" />; } return null; } return this.props.children; } } ErrorBoundary.propTypes = { page: PropTypes.bool } ErrorBoundary.defaultProps = { page: false } const compose = (Component, option = {}) => { if (typeof Component !== 'function') { throw ('Component not function'); } return React.forwardRef((props, ref) => ( <ErrorBoundary {...option}> { React.cloneElement(<Component />, Object.assign({ ref }, props)) } </ErrorBoundary> )) } /** * 外抛方法 用于包裹组件 * 使用示例如下 * * 方式一 高阶函数 * @ErrorBoundary.WrapComponent * class Component extends React.Component {} * * 方式二 高阶函数带配置项 * @ErrorBoundary.WrapComponent(option) * class Component extends React.Component {} * * 方式三 方法调用 * ErrorBoundary.WrapComponent(Component, option) * */ ErrorBoundary.WrapComponent = function (arg1, arg2) { if (typeof arg1 === 'function') { return compose(arg1, arg2); } else { return Component => compose(Component, arg1); } } export default ErrorBoundary; ~~~