如何让我的Collapse组件在reactjs应用中工作?

问题描述 投票:0回答:1

看看下面的代码,我使用了reactstrap的 "Collapse "组件,但它没有发挥应有的作用。

import { Component } from "react";
import React from "react";
import { Collapse, Navbar } from "reactstrap";
class Main extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false
    };
  }
  show() {
    this.setState({
      open: !this.state.open
    });
  }
  render() {
    return (
      <>
        <button onClick={() => this.show()}>Show</button>
        <Collapse isOpen={this.state.open} navbar>
          <Navbar>hello</Navbar>
        </Collapse>
      </>
    );
  }
}
export default Main;
html reactjs reactstrap
1个回答
0
投票

我认为问题出在你的show方法上,因为this.state是异步更新的。正确的语法应该是如下。

show() {
    this.setState(prevState => ({ open: !prevState.open}));
}

你可以参考这个文档 https:/reactjs.orgdocsstate-and-lifecycle.html#stat-updates-may-be-asynchronous。

© www.soinside.com 2019 - 2024. All rights reserved.