[英]React call a function from wrapper component
I am not that experienced with React, but i've been assigned to an existing complex React project.我对 React 没有那么丰富的经验,但我被分配到一个现有的复杂 React 项目。 I have a popup that only showed once but it can load a particular component.
我有一个仅显示一次但可以加载特定组件的弹出窗口。 I want to close a popup by the button from other components, actually the function to close popup exists in wrapper component, but how to call it from the non-class component?
我想通过其他组件的按钮关闭弹出窗口,实际上function关闭弹出窗口存在于包装组件中,但是如何从非类组件中调用它?
I have a popup called ModalView.jsx
, it's a wrapper:我有一个名为
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>
);
}
}
and i have a component that be showed in {showedComponent}
called MyCard.jsx
:我有一个在
{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>
...
);
};
So how to call onCancel()
function from ModalView.jsx
to MyCard
const component?那么如何从
ModalView.jsx
调用 onCancel onCancel()
function 到MyCard
const 组件呢?
You can use render prop pattern here:您可以在此处使用渲染道具模式:
// 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>
);
Now ChildComponent
has close
props containing onClose
handler.现在
ChildComponent
具有包含onClose
处理程序的close
道具。
PS: By the way, it's better to avoid creating callbacks on each render, you can declare your onClose
handler on class level instead of render()
function: PS:顺便说一句,最好避免在每次渲染时创建回调,您可以在 class 级别而不是
render()
function 上声明onClose
处理程序:
class ModalView extends Component {
onClose = () => { ... }
render() {
// use this.onClose instead
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.