【问题标题】:Using React Hooks in classes [duplicate]在类中使用 React Hooks [重复]
【发布时间】:2020-06-07 10:13:36
【问题描述】:

我对 React 还很陌生,目前在使用 react 钩子时遇到了一些问题。我在构造函数中初始化了 show 和 setShow ,但是我得到一个错误,说 show 和 setShow 在渲染函数中是未定义的。我有类似的东西:

export default class Projects extends Component {
  constructor(props) {
    super(props);
    const [show, setShow] = useState(false);    //Where I initialize show and setShow
    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);
  }

  render() {
    return (
      <div class="projects-section" id="projects">
        <img className="project-image" src="assets/UAS-frontend.png" onClick={handleShow}/>
        <Modal show={show} onHide={handleClose}>    //Where I get the error
          <Modal.Header closeButton></Modal.Header>
          <Modal.Footer>
            <Button variant="secondary" onClick={handleClose}>
              Close
            </Button>
            <Button variant="primary" onClick={handleClose}>
              Save Changes
            </Button>
          </Modal.Footer>
        </Modal>
      </div>
    )
  }
}

【问题讨论】:

标签: reactjs react-hooks


【解决方案1】:

用于状态管理的 React 钩子用于函数组件中。 在您的情况下,您可以使用旧学校状态对象:

constructor(props) {
  super(props);
  this.state = {
    show: false,
  }
}

如果您想改用 React Hooks,请执行以下操作:

const Projects = (props) => {
  const [show, setShow] = useState(false);

  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);

  return (
    <div class="projects-section" id="projects">
      <img className="project-image" src="assets/UAS-frontend.png" onClick={handleShow}/>
      <Modal show={show} onHide={handleClose}>    //Where I get the error
        <Modal.Header closeButton></Modal.Header>
        <Modal.Footer>
          <Button variant="secondary" onClick={handleClose}>
            Close
          </Button>
          <Button variant="primary" onClick={handleClose}>
            Save Changes
          </Button>
        </Modal.Footer>
      </Modal>
    </div>
  )
}

【讨论】:

  • 天啊。半年现在是“老派”
  • 好时光@YuryTarabanko
猜你喜欢
  • 2019-10-30
  • 2021-10-06
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
  • 2019-08-27
  • 2019-09-14
  • 2020-07-06
相关资源
最近更新 更多