只需单击按钮即可打开模态 [英] opening a modal with the click of a button
问题描述
下面的代码使用Modal react组件:
The next code uses a Modal react component:
export class AddWorkLogEditor extends React.Component {
constructor(props) {
super(props);
this.addWorkLog = this.addWorkLog.bind(this);
this.onOpenModal = this.onOpenModal.bind(this);
this.onCloseModal = this.onCloseModal.bind(this);
this.state = {
open:true
};
}
onOpenModal() {
this.setState({open: this.props.openModal});
}
onCloseModal() {
this.setState({open:false});
}
addWorkLog() {
}
render() {
const bstyle = {
backgroundColor: 'green',
textAlign:"left",
paddingLeft: '0px',
color: 'white'
};
const {open} = this.state;
return (
<div>
<Modal open={open} onClose={this.onCloseModal} little>
<h3>hi gi</h3>
<Button bsStyle="success" bsSize="small" onClick ={(ev) => {console.log(ev)} }> Save </Button>
</Modal>
</div>
);
}
}
我正试图使用:
addWorkLog()
{
return <AddWorkLogEditor/>;
}
和
createAddWorkLogButton () {
return (
<button style={ { color: '#007a86'} } onClick={this.addWorkLog} >Add Work Log</button>
);
}
我的意思是,当我单击此按钮后,什么都没有显示.还有另一种方法可以调用该模式吗?我从以下位置导入模式:
I mean, after I click at this button nothing shows up. Is there another way to call that modal? I am importing the modal from:
从反应模式"中导入模态
import Modal from 'react-responsive-modal'
推荐答案
您试图仅在单击按钮后才渲染模态,这对于非反应性环境来说是很自然的,但在反应中它会以不同的方式起作用.在最简单的解决方案中,应始终呈现Modal
,并且当用户单击按钮时,将模式open
属性更改为true
.
You are trying to render the modal only once the button is clicked, while that's quite natural for non-react environments, in react it works in a different way. In the simplest solution the Modal
should be always rendered, and when a user clicks the button you change the modal open
property to true
.
{ /* all the markup of your page */ }
<button onClick={() => this.setState({showModal: true})}>Add Work Log</button>
{ /* anything else */ }
{ /* modal is here but it is hidden */ }
<Modal open={this.state.showModal}>...</Modal>
或者,您可以完全跳过模式渲染,直到showModal
变为true.
Alternatively, you can just skip the modal rendering at all until the showModal
becomes true.
this.state.showModal && <Modal open>...</Modal>
这篇关于只需单击按钮即可打开模态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!