我在尝试弄清楚如何在我的模态构造函数/props中添加一个功能正常的关闭按钮时遇到了很多问题--构造器/道具一直不起作用,我不确定在按钮元素中的onClick=之后添加什么。
class Modal extends React.Component {
// whenever component gets rendered to the screen we create a new div assigned to this.modalTarget
componentDidMount() {
this.modalTarget = document.createElement('div');
// add class name to modal target
this.modalTarget.className = 'modal';
// take the div we just created and append it to the body tag in doc
document.body.appendChild(this.modalTarget);
// call method _render
this._render();
}
// whenever the component's about to update we do another render
// this render makes sure that if we get a new set of components or children in the modal
// we're going to render those to the parent div as well
componentWillUpdate() {
this._render();
}
// clean up - whenever the component is about to unmount from the screen
// cleans up dom when the modal is removed from the component heirarchy
componentWillUnmount() {
// unmounts this.props.children
ReactDOM.unmountComponentAtNode(this.modalTarget);
document.body.removeChild(this.modalTarget);
}
_render() {
// take react dom library and render a div that contains this.props.children
// and render it into this.modalTarget
ReactDOM.render(
<Provider store= {store}>
<Router>
<div className="modal">
{this.props.children}
<button>Close</button>
</div>
</Router>
</Provider>,
this.modalTarget
发布于 2019-04-25 03:16:49
看起来你的模式是开放的,仅仅基于它是否是由父级呈现的。除了一起重新设计这个模式之外,实现您想要的唯一方法是传入某种onClose回调:
class Parent extends React.Component {
state = { isModalOpen: false };
render() {
return (<div>
// Stuff
{this.state.isModalOpen &&
<Modal onClose={() => this.setState({ isModalOpen: false })}/>
}
// Stuff
</div>);
}
}
在你的Modal
中
<div className="modal">
{this.props.children}
<button onClick={this.props.onClose}>Close</button>
</div>
https://stackoverflow.com/questions/55836921
复制相似问题