我是React的新手,我想使用React-Bootstrap Modal.这段代码很好用,但是我想做的是在Trigger组件中没有按钮,而是在另一个父组件中使用它,以便可以从父组件中的按钮调用Trigger组件.
let Button = ReactBootstrap.Button;
let Modal = ReactBootstrap.Modal;
class Trigger extends React.Component{
constructor(props){
super(props);
this.state = { show: false };
}
render(){
let close = () => this.setState({ show: false});
return (
<div className="modal-container" style={{height: 1000}}>
<Button
bsStyle="primary"
bsSize="large"
onClick={() => this.setState({ show: true})}
>
Launch contained modal
</Button>
<Modal
show={this.state.show}
onHide={close}
container={this}
aria-labelledby="contained-modal-title"
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title">Edit Recipe</Modal.Title>
</Modal.Header>
<Modal.Body>
<form className="form-group">
<label>Recipe</label>
<input type='text' className="form-control"/>
<label>Ingredients</label>
<textarea type='text' className="form-control"/>
</form>
</Modal.Body>
<Modal.Footer>
<Button bsStyle="primary">Edit Recipe</Button>
<Button onClick={close}>Close</Button>
</Modal.Footer>
</Modal>
</div>
);
}
}
解决方法:
观察代码后,您会发现Modal get的onClick of Button启动了.组件中相应的状态更改是其状态的show属性.
我制作了以下jsFiddle,以展示如何从外部控制模式.
https://jsfiddle.net/sunnykgupta/5qrzt9uy/
总的来说,我们接受一个支持到组件中并支持更改(通过componentWillReceiveProps()).
在内部,我们维护一个状态以跟踪模式显示状态.
码:
let Button = ReactBootstrap.Button;
let Modal = ReactBootstrap.Modal;
class Trigger extends React.Component{
constructor(props){
super(props);
this.state = { show: props.modal };
}
componentWillReceiveProps(nextProps){
if(this.state.show!==nextProps.modal){
this.setState({show: nextProps.modal})
}
}
render(){
let close = () => this.setState({ show: false});
return (
<div className="modal-container">
<Modal
show={this.state.show}
onHide={close}
container={this}
aria-labelledby="contained-modal-title"
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title">Edit Recipe</Modal.Title>
</Modal.Header>
<Modal.Body>
<form className="form-group">
<label>Recipe</label>
<input type='text' className="form-control"/>
<label>Ingredients</label>
<textarea type='text' className="form-control"/>
</form>
</Modal.Body>
<Modal.Footer>
<Button bsStyle="primary">Edit Recipe</Button>
<Button onClick={close}>Close</Button>
</Modal.Footer>
</Modal>
</div>
);
}
}
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {show: false}
}
render(){
return <main>
<Trigger modal={this.state.show}/>
<Button
bsStyle="primary"
bsSize="large"
onClick={() => this.setState({ show: true})}
>
Launch contained modal
</Button>
</main>
}
}
ReactDOM.render(
<Parent/>,
document.getElementById('container')
);