我在试图弄清楚如何向我的模态添加一个功能正常的关闭按钮时遇到了很多问题 - 构造函数/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