繁体   English   中英

从 React Js 中的 Hook Modal 调用 function

[英]Calling function from Hook Modal in React Js

我正在尝试从 React js 中的模态钩子调用函数(更新状态)。 但是,它不会更新 state。 但是,当我在 function 中写入警报时,它可以工作,但 setState 不能。 有什么问题????

主要部件

this.state = {
      message: false
}

showMessage(){
  alert(" hhh");  //works
  // this.setState({message:true})  //does not work
}

<ExcludeHolidayModal confirmExHol={this.showMessage}/>

模态

function ExcludeHolidayModal(props) {
    const [show, setShow] = useState(false);
    const handleClose = () => setShow(false);
    const handleShow = () => {setShow(true)};
    const [date, setDate] = useState(new DateObject());

    const excludeHolidays = (dates) => {
      API.excludeHolidays(dates).then(() => {
          handleClose();
          setDate(new DateObject());
          props.confirmExHol();  //Calling function here <------------
        })
        .catch((err) => {
          if (err.status === 401) {
          }
        });
    }

    return (
      <>
        <Button onClick={handleShow} data-testid="help-button" variant="info">
            </Button>  
        <Modal
          show={show}
          onHide={handleClose}
          backdrop="static"
          keyboard={false}
        >
          <Modal.Header closeButton>
            <Modal.Title>Choose Holidays</Modal.Title>
          </Modal.Header>
          <Modal.Body>
          <DatePicker 
                value={date} 
                 onChange={setDate}
                 multiple={true}/>
          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={() => excludeHolidays(date)}>Send</Button>
          </Modal.Footer>
        </Modal>
      </>
    );
  }
  
  export default ExcludeHolidayModal;

请试试这个:

this.state = {
      message: false
}

showMessage = () => {
  // alert(" hhh");  //works
  this.setState({message:true})  //does not work
}

<ExcludeHolidayModal confirmExHol={this.showMessage}/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM