我正在使用React和react-bootstrap编写一个简单的webapp。我有两个按钮,应该打开两个不同的模态。我想将包含Buttons的Class与两个Modal Classes分开,例如
var React = require('react');
var ReactDOM = require('react-dom');
import { Button, Modal, closeButton } from 'react-bootstrap';
var Jumbo = React.createClass ({
render() {
return (
<div className="container">
<Button onClick={Modal1.open}>Modal1</Button>
<Button onClick={Modal2.open}>Modal2</Button>
<Modal1 />
<Modal2 />
</div>
);
}
});
var Modal1 = React.createClass ({
getInitialState() {
return {
showModal: false
};
},
close() {
this.setState({
showModal: false
});
},
open() {
this.setState({
showModal: true
});
},
render() {
return (
<Modal show={this.state.showModal} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>Modal1</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Modal1</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.close}>Close</Button>
</Modal.Footer>
</Modal>
);
}
});
var Modal2 = React.createClass ({
getInitialState() {
return {
showModal: false
};
},
close() {
this.setState({
showModal: false
});
},
open() {
this.setState({
showModal: true
});
},
render() {
return (
<Modal show={this.state.showModal} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>Modal2</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Modal2</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.close}>Close</Button>
</Modal.Footer>
</Modal>
);
}
});
ReactDOM.render(<Jumbo />, document.getElementById('modal'));
但是onClick={ModalN.open}
不起作用。通常我会将Button放在模态类中(按照the documented example)并执行onClick={this.open}
,但我想将两个Button元素放在一起,而不是放在单独的<div>
中。传递Modal参考的正确方法是什么?
答案 0 :(得分:0)
onClick={modalN.open}
无效,您需要在ModalN
中加入Jumbo
组件:
var Jumbo = React.createClass ({
getInitialState() {
return {
activeModal: null
}
},
openModal(id){
this.setState({
activeModal: id
})
}
render() {
return (
<div className="container">
<Button onClick={this.openModal.bind(this,1)}>Modal1</Button>
<Button onClick={this.openModal.bind(this,2)}>Modal2</Button>
{this.state.activeModal === 1 ? <Modal1 /> :null}
{this.state.activeModal === 2? <Modal2 /> : null}
</div>
);
}
});
您还需要将每个模态的初始showModal
更改为true
,否则他们将无法显示(因为永远不会调用open()
):
var Modal1 = React.createClass ({
getInitialState() {
return {
showModal: true
}
},
...
});