Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

自定义组件实现对外暴露生命周期回调 #13

Open
leviosa-e opened this issue May 15, 2024 · 0 comments
Open

自定义组件实现对外暴露生命周期回调 #13

leviosa-e opened this issue May 15, 2024 · 0 comments

Comments

@leviosa-e
Copy link
Owner

需求场景:

使用组件的业务方需要感知到自定义组件渲染完成时,执行相应的逻辑。

实现原理:

  • 接收外部传入的回调方法
  • 组件内部在相应的时机进行执行

代码实现:

interface IProps {
  biz: string;
  theme?: 'light' | 'dark';
  customClass?: string;
  customStyle?: CSSProperties;
  onReady?: (show: boolean) => void;
}

export default class ComponentA extends React.Component {

  componentDidMount() {
      new NoticeConfig(this.props.biz)
        .getNotice()
        .then((notice) => {
          const show = !!notice?.content && !notice.rehearsal;
          if (show) {
            this.setState({ content: notice.content }, this.checkOverflow);
          }
          this.onReady(show);
        })
        .catch(() => {
          this.onReady(false);
        });
    }

  private onReady = (show: boolean) => {
      try {
        this.props.onReady?.(show);
      } catch (error) {
        // Convert to unhandled rejection to avoid crashing
        Promise.reject(
          new Error(
            `Error occured in \`onReady\` of <ComponentA />: ${
              (error as Error | undefined)?.message || error || 'unknown'
            }`,
          ),
        );
      }
    };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant