首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >关闭React Modal

关闭React Modal
EN

Stack Overflow用户
提问于 2019-04-25 03:02:34
回答 1查看 15.4K关注 0票数 0

我在尝试弄清楚如何在我的模态构造函数/props中添加一个功能正常的关闭按钮时遇到了很多问题--构造器/道具一直不起作用,我不确定在按钮元素中的onClick=之后添加什么。

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

发布于 2019-04-25 03:16:49

看起来你的模式是开放的,仅仅基于它是否是由父级呈现的。除了一起重新设计这个模式之外,实现您想要的唯一方法是传入某种onClose回调:

代码语言:javascript
复制
class Parent extends React.Component {
  state = { isModalOpen: false };

  render() {
    return (<div>
      // Stuff
      {this.state.isModalOpen &&
        <Modal onClose={() => this.setState({ isModalOpen: false })}/>
      }
      // Stuff
    </div>);
  }
}

在你的Modal

代码语言:javascript
复制
<div className="modal">
    {this.props.children}
    <button onClick={this.props.onClose}>Close</button>
</div>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55836921

复制
相关文章

相似问题

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