反应模态设置状态不起作用

React-modal setstate not working

export class StartContainer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showModal: false
        };

    }

    handleOpenModal = () => {
        console.log("Here")
        //this.setState({ showModal: true }, () =>{ console.log(this.state) });
        this.setState(() => {
            console.log("Changing state")
            return { showModal: true }
          });
    }

    handleCloseModal = () => {
        console.log(this.state.showModal)
        this.setState( );
    }


    render() {
        console.log(this.state)
        return (
            <div>
                <StartComponent handleModalOpen={this.handleOpenModal} />
                <ReactModal
                    isOpen={this.state.showModal}
                    contentLabel="Minimal Modal Example"
                >asda
                    <button onClick={this.handleCloseModal}>Close Modal</button>
                </ReactModal>
            </div>
        )
    }
}

所以我正在尝试将 react-modal 集成到我的项目中。

未调用 this.setState() 方法我没有看到控制台日志,当我将回调传递给 setState() 方法时也没有。

有人可以帮我吗?

谢谢你的时间!

UPDATE -- 开始组件代码。

export const StartComponent = (props) => (
<div className="start-page">
    <div className="container">
        <div className="row">
            <div className="col-sm-6">
                <NavLink to="/start/klarungsfalle">Einträge prüfen</NavLink>
            </div>
            <div className="col-sm-6" >
                <NavLink onClick={props.handleModalOpen} style={{ background: "#aac4d3", cursor: "default" }} to="/">Einträge verfügen</NavLink>
            </div>
        </div>
    </div>
</div>

);

另外我不得不提一下,我也在使用 redux

问题似乎是在处理事件时缺少 es6 所需的一些绑定。因此,对于访问状态的处理程序,只需将这些绑定放入您的构造函数中即可:

constructor() {
    super();
    this.state = {
        showModal: false
    };
    // bindings
    this.handleOpenModal = this.handleOpenModal.bind(this);
    this.handleCloseModal = this.handleCloseModal.bind(this);
}

那里不需要匿名函数:

 handleOpenModal() {
    this.setState({showModal: true});
}

handleCloseModal() {
    this.setState({showModal: false});
}

将回调传递给 setState 意味着当 setState 完成时它将 运行 接下来执行该函数; setState 是异步的,但这对您没有帮助。为您的 StartComponent 组件提供代码可能会有所帮助,因为您的处理程序函数可能未被调用。

尝试onClick={() => props.handleModalOpen()}

注意:只是一个建议,考虑将您的道具命名为子项中与父项中相同的名称,因为 handleModalOpen 和 handleOpenModal 可能会让人混淆。

你的代码似乎对我有用。我刚刚设置了 <StartComponent />,状态看起来就像你想要的那样。

尝试使用您的代码的以下代码段:

或者你可以看看这个 CodePen Demo.

const { HashRouter, NavLink } = ReactRouterDOM;

const App = () => (
  <HashRouter>
    <Modal />
  </HashRouter>
);

const StartComponent = ({currentState, handleModalOpen, handleNix}) => (
  <div className="start-page">
    <div className="container">
      <div className="row">
        <div className="col-sm-6">
          <NavLink to="/start/klarungsfalle" onClick={handleNix}>Einträge prüfen</NavLink>
        </div>
        <div className="col-sm-6">
          <NavLink
            onClick={handleModalOpen}
            style={{ background: "#aac4d3", cursor: "default" }}
            to="/"
            >
            Einträge verfügen
          </NavLink>
        </div>
      </div>
      <div className='row justify-center'>
        <div className='col-xs-12'>
          <div>
            <code>Modal</code> state
            <pre>{JSON.stringify(currentState)}</pre>
          </div>
        </div>
      </div>
    </div>
  </div>
);


class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showModal: false
    };
  }

  handleOpenModal = () => {
    console.log("Here");
    this.setState(() => {
      console.log(`Changing state to 'showModal: ${this.state.showModal}'`);
      return { showModal: true };
    });
  };
  
  handleNix = () => {
    alert("hier gibt's nichts");
  }

  handleCloseModal = () => {
    console.log(this.state.showModal);
    this.setState(() => {
      console.log(`Changing state to 'showModal: ${this.state.showModal}'`);
      return { showModal: false };
    });
  };

  render() {
    console.log(this.state);
    return (
      <div className="container">
        <StartComponent
          handleModalOpen={this.handleOpenModal}
          handleNix={this.handleNix}
          currentState={this.state}/>
        <ReactModal
          isOpen={this.state.showModal}
          contentLabel="Minimal Modal Example">
          <div className="flex columns-center">
            <div className="note">
              The modal hides the Stack Overflow console. Look behind the modal
              or open your JS console.
            </div>
            <div className="flex">
              <div>
                <code>Modal</code> state
                <pre>{JSON.stringify(this.state)}</pre>
              </div>
              <button
                className="btn btn-sm btn-danger"
                onClick={this.handleCloseModal}>
                Close Modal
              </button>
            </div>
          </div>
        </ReactModal>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));
.flex {
  display: flex;
}

.justify-center {
  justify-content: center;
}

.space-around {
  justify-content: space-around;
}

.columns-center {
  flex-direction: column;
  align-items: center;
}

.note {
  font-size: 0.7em;
  margin-bottom: 1rem;
}

.btn:after {
  content: "F436";
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" />

<div id="app"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-modal/2.3.2/react-modal.min.js"></script>

您必须绑定函数才能使用 'this' 关键字

 constructor() {
    super();
    this.state = {
        showModal: false
    };
    this.handleOpenModal = this.handleOpenModal.bind(this);
    this.handleCloseModal = this.handleCloseModal.bind(this);
}