Uncaught TypeError:windowWidth不是一个函数[关闭]

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

[我不断收到错误:未捕获的TypeError:windowWidth不是一个函数-我该如何解决,请参见下面的代码-我试图创建关于我们的页面,该页面响应两个图像?

import React, { useState, useEffect } from 'react';
import classes from './styles.module.scss';
import chair from './chair.png';
import chairmob from './chairmob.png';

const About = () => {
  const [windowWidth, setWindowWidth] = useState(window.innerWidth);

  const imageUrl = windowWidth() >= 600 ? chair : chairmob;

  const handleWindowResize = () => {
    setWindowWidth(window.innerWidth);
  };

  useEffect(() => {
    window.addEventListener('resize', handleWindowResize);

    return () => {
      window.removeEventListener('resize', handleWindowResize);
    };
  });

  return (
    // <div className={classes.About}>
    <div className="About" style={{ backgroundImage: `url(${imageUrl})` }}>
      <div className="About-content">
        <h1>oh hello</h1>
        <p>
          We're Homewa,<br></br> the first property <br></br>
          search platform that <br></br>actually puts the <br></br>you first.{' '}
        </p>
      </div>
    </div>
    // </div>
  );
};

export default About;
reactjs scss-mixins
1个回答
2
投票

您有错字:windowWidth不是函数:

//                not windowWidth()
const imageUrl = windowWidth >= 600 ? chair : chairmob;

此外,您应该仅在安装座上设置事件监听器,而不是在当前设置的每个渲染器上设置事件监听器:

  useEffect(() => {
    const handleWindowResize = () => {
      setWindowWidth(window.innerWidth);
    };

    window.addEventListener('resize', handleWindowResize);

    return () => {
      window.removeEventListener('resize', handleWindowResize);
    };
  }, []);
© www.soinside.com 2019 - 2024. All rights reserved.