我对React没有太多经验,但我已经被分配到一个现有的复杂React项目中。我有一个弹出式窗口,只显示一次,但它可以加载一个特定的组件。我想通过其他组件的按钮来关闭弹出窗口,实际上关闭弹出窗口的函数存在于包装器组件中,但是如何从非类组件调用它呢?
我有一个名为ModalView.jsx
的弹出窗口,它是一个包装器:
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
的组件:
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
常量组件呢?
发布于 2019-09-27 16:54:37
你可以在这里使用渲染属性模式:
// 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()
函数:
class ModalView extends Component {
onClose = () => { ... }
render() {
// use this.onClose instead
}
}
https://stackoverflow.com/questions/58130990
复制相似问题