简体   繁体   English

反应:在 onClick 中调用 function 返回 undefined

[英]React: calling a function in the onClick returns undefined

I'm trying to write a code that shows a list of images, etc. based on this answer: https://stackoverflow.com/a/57635373/9478434我正在尝试根据以下答案编写显示图像列表等的代码: https://stackoverflow.com/a/57635373/9478434

My code is:我的代码是:

class ImageGallery extends Component {
  constructor(props) {
    super(props);
    this.state = {
      photoIndex: 0,
      isOpen: false,
      imageList: [],
    };
  }

  getImages() {
    axios
      .get(IMAGE_LIST_URL, {})
      .then((response) => {
        const data = response.data;
        console.log(data);
        this.setState({ imageList: response.data });
      })

      .catch((error) => {
        setTimeout(() => {
          console.log(error.response.data.message);
        }, 200);
      });
  }

  componentDidMount() {
    this.getImages();
  }
  changePhotoIndex(imgIndex) {
    this.setState({ photoIndex: imgIndex, isOpen: true });
  }

  render() {
    const { photoIndex, isOpen, imageList } = this.state;
    const singleImage = imageList.map(function (img, imgIndex) {
      const imagePath = `http://localhost:8000/media/${img.filePath}`;

      console.log(imagePath);
      return (
        <figure className="col-xl-3 col-sm-6">
          <img
            src={imagePath}
            alt="Gallery"
            className="img-thumbnail"
            onClick={() => this.changePhotoIndex(imgIndex)}
          />
        </figure>
      );
    });
    return <div>{singleImage}</div>;
  }
}

However while clicking on the image, I get a type error (t is undefined) in the console regarding to the line onClick={() => this.changePhotoIndex(imgIndex) and the state of app does not change.但是,在单击图像时,我在控制台中收到关于onClick={() => this.changePhotoIndex(imgIndex)行的类型错误(t 未定义),并且应用程序的 state 没有改变。

The changePhoneIndex function considers itself and not the component as this . changePhoneIndex function 认为它自己而不是组件this

You can bind it to the component itself and be able to access setState by adding this to the constructor:您可以将它绑定到组件本身,并能够通过将其添加到构造函数来访问setState

constructor(props) {
    super(props);
    this.state = {
      photoIndex: 0,
      isOpen: false,
      imageList: [],
    };

    this.changePhotoIndex.bind(this);
  }

Or you can call set state directly:或者你可以直接调用set state:

onClick={() => this.setState({ photoIndex: imgIndex, isOpen: true })}

You forgot to bind your function.你忘了绑定你的 function。 Add the following to your code:将以下内容添加到您的代码中:

constructor(props) {
    super(props);
    this.state = {
      photoIndex: 0,
      isOpen: false,
      imageList: [],
    };
    this.changePhotoIndex = this.changePhotoIndex.bind(this); // missing
  }

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

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