我正在使用react.js创建一个web应用程序,它也使用react引导程序。
我想要完成的是当用户点击按钮,然后模态将出现,但这是没有发生。
按钮码
<div className="rightButtons">
<button name="updateItem" className="btn btn-primary" onClick={() => { this.onUpdateItem(this.props.selectedAppTypeId)}} >Update Item</button>
</div>
函数,将被调用。
onUpdateItem = (id) => {
return (
<div className="static-modal">
<Modal.Dialog>
<Modal.Header>
<Modal.Title>Modal title</Modal.Title>
</Modal.Header>
<Modal.Body>One fine body...</Modal.Body>
<Modal.Footer>
<Button>Close</Button>
<Button bsStyle="primary">Save changes</Button>
</Modal.Footer>
</Modal.Dialog>
</div>
);
}
任何帮助都是很大的帮助。谢谢。
发布于 2018-08-20 20:08:17
将HTML返回到您的onClick处理程序中,而不是返回到组件的呈现方法中。如果要在onClick之后显示HTML,则需要在实际呈现中实际返回这些HTML元素。试试这个:
class Component extends React.Component {
state = {
showModal: false
}
renderModal = () => {
return (
<div className="static-modal">
<Modal.Dialog>
<Modal.Header>
<Modal.Title>Modal title</Modal.Title>
</Modal.Header>
<Modal.Body>One fine body...</Modal.Body>
<Modal.Footer>
<Button>Close</Button>
<Button bsStyle="primary">Save changes</Button>
</Modal.Footer>
</Modal.Dialog>
</div>
);
}
render() {
return(
<div>
<button onClick={() => this.setState({showModal:true})}> Show </button>
{this.state.showModal && this.renderModal()}
</div>
)
}
}
编辑:您还可以将整个Modal返回语句导出到它自己的组件中,并在showModal状态为真时有条件地呈现该组件。
const ModalComponent = (props) => {
return(
<div className="static-modal">
<Modal.Dialog>
<Modal.Header>
<Modal.Title>Modal title</Modal.Title>
</Modal.Header>
<Modal.Body>One fine body...</Modal.Body>
<Modal.Footer>
<Button>Close</Button>
<Button bsStyle="primary">Save changes</Button>
</Modal.Footer>
</Modal.Dialog>
</div>
)
}
class ParentComponent extends React.Component {
state = {
showModal: false
}
render(){
return(
<div>
<button onClick={() => this.setState({showModal:true})}>
Show Modal
</button>
{this.state.showModal && <ModalComponent id='0af141random'/>}
</div>
)
}
}
发布于 2018-08-20 20:07:59
您遇到的问题是,您将一个react函数组件作为事件处理程序传递;函数的返回值是一个react组件,但是调用函数本身不会在DOM中挂载该组件并显示它。
实现这一目标的一个更好的方法可能是将Modal组件放置在组件中,并控制是否通过使用回调来更改父组件的状态来显示它。
就像这样:
class ParentComponent extends React.Component {
showModal() {
this.setState{
modalActive: true;
}
}
render() {
<div>
<Button onClick={showModal}>Show me the modal!</Button>
<Modal active={this.state.modalActive} />
</div>
}
}
const modalComponent = (props) => {
return (<div style={{ display: (props.isActive) ? "block" : "none "}}>
<h1>I'm a modal!</h1>
</div>)
}
我还没有检查过,但我肯定有自己的道具来显示/隐藏调制解调器。
编辑:下面是react引导文档中的代码示例,显示了它在使用中的https://react-bootstrap.github.io/components/modal/#modals-live
https://stackoverflow.com/questions/51941282
复制相似问题