下面是App类组件,页面完全加载后,我想在其中打开Modal。我也尝试使用componentDidMount()生命周期方法,但失败。
class App extends React.Component {
constructor(props){
super(props);
this.handleSHow = this.handleShow.bind(this);
this.state = {
modalState : true
}
}
handleShow = () => {
this.setState(()=>{
return{
modalState : false
};
});
}
render()
{
console.log(this.state.modalState)
return(
<div>
<h1 className="main-title">My Profile</h1>
<MainContent />
</div>
)
}
}
export default App;
您可以做这样的事情
class App extends React.Component {
constructor(props){
super(props);
this.handleSHow = this.handleShow.bind(this);
this.state = {
modalState : false
}
}
componentDidMount(){
this.setState({
modalState : true
})
}
render()
{
console.log(this.state.modalState)
return(
<div>
{this.state.modalState ? <YourModal/> : null}
<h1 className="main-title">My Profile</h1>
<MainContent />
</div>
)
}
}
export default App;
假设您正在使用Bootstrap Modal,这是一个基本示例:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
modalState: true
};
this.handleShow = this.handleShow.bind(this);
}
handleShow() {
this.setState({ modalState: !this.state.modalState });
}
render() {
return (
<div>
<div className={"modal fade" + (this.state.modalState ? " show d-block" : " d-none")} tabIndex="-1" role="dialog">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">My Profile</h5>
<button type="button" className="close" onClick={this.handleShow}>
<span>×</span>
</button>
</div>
<div className="modal-body">...</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" onClick={this.handleShow}>Close</button>
<button type="button" className="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>