首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >React从包装器组件调用函数

React从包装器组件调用函数
EN

Stack Overflow用户
提问于 2019-09-27 16:47:49
回答 1查看 647关注 0票数 0

我对React没有太多经验,但我已经被分配到一个现有的复杂React项目中。我有一个弹出式窗口,只显示一次,但它可以加载一个特定的组件。我想通过其他组件的按钮来关闭弹出窗口,实际上关闭弹出窗口的函数存在于包装器组件中,但是如何从非类组件调用它呢?

我有一个名为ModalView.jsx的弹出窗口,它是一个包装器:

代码语言:javascript
运行
复制
class ModalView extends Component {
  static propTypes = {
    //...
    isShow: PropTypes.bool,
  };
  static defaultProps = {
    isShow: false,
  }
  render() {
    const {
      isShow,
      showedComponent,
    } = this.props;

    onCancel = () => {
      const { showPagePopup } = this.props;
      showPagePopup({ isShow: false });
    }
    return (
      <div
        className={cx('page-popup modal fade', {
          'd-block show': isShow,
        })}
        tabIndex="-1"
        role="dialog"
        aria-hidden="true"
      >
        <div className="modal-dialog" role="document">
          <div className="modal-content">
            <button type="button" className="close close-modal" data-dismiss="modal" aria-label="Close" onClick={() => this.onCancel()}>
              <IconCloseModal width="14" height="14" className="icon icon-close" />
            </button>
            <div className="modal-body">
              {showedComponent}
            </div>
          </div>
        </div>
      </div>
    );
  }
}

我有一个在{showedComponent}中显示的叫做MyCard.jsx的组件:

代码语言:javascript
运行
复制
const MyCard = ({
myRules = isShow
}) => {
    const openPage = () => {
      // -------how to call onCancel() function from ModalView.jsx in this line?--------
      var pageUrl = `xxx`;
      setTimeout(function(){
        window.open(pageUrl, '_blank');
      }, 3000);
    }
return (
  ...
  <PrimaryButton onClick={() => openPage()} className="hide-for-print-version ml-3">
     Open Page
  </PrimaryButton>
  ...
);
};

那么如何从ModalView.jsx调用onCancel()函数到MyCard常量组件呢?

EN

Stack Overflow用户

发布于 2019-09-27 16:54:37

你可以在这里使用渲染属性模式:

代码语言:javascript
运行
复制
// modal
  ...
  render() {
    const { children: renderProp } = this.props;

    return (
      <div className="modal-body">
        {renderProp(onClose)}
      </div>
    );
  }
  ...

// using modal
// instead of
return (
  <Modal>
    <ChildComponent />
  </Modal>
);

// use

return (
  <Modal>
    {close => <ChildComponent close={ close } />
  </Modal>
);

现在ChildComponent有了包含onClose处理程序的close属性。

顺便说一下,最好避免在每次渲染时都创建回调,你可以在类级别上声明你的onClose处理程序,而不是render()函数:

代码语言:javascript
运行
复制
class ModalView extends Component {
  onClose = () => { ... }

  render() {
    // use this.onClose instead
  }
}
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58130990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档