gpt4 book ai didi

javascript - ReactJS - Uncaught ReferenceError : function is not defined

转载 作者:行者123 更新时间:2023-11-30 15:58:31 27 4
gpt4 key购买 nike

我是 reactJs 的新手,我遇到了未定义函数的问题。

如我所见,我在构造函数中定义了它,但是..

bundle.js:758 Uncaught ReferenceError: myCallback is not defined.

import React from "react";
import ReactDOM from "react-dom";
import Vivus from "vivus";

export default class MySkills extends React.Component {
constructor() {
super();
this.state = {visable: false};
this.onScroll = this.onScroll.bind(this);
this.myCallback = this.myCallback.bind(this);
}

componentDidMount() {
document.addEventListener('scroll', this.onScroll);
}

myCallback() {
alert("myCallback");
}

onScroll() {
var scrollY = window.scrollY;
if (scrollY > 2300 && this.state.visable === false) {
new Vivus("foo", {duration: 100, file: 'bar'}, myCallback.bind(this));
}
}

也许有人可以更好地解释函数的绑定(bind)?它似乎与 onScrool 函数一起工作,但 myCallback 函数不起作用。

谢谢!

最佳答案

你在你的构造函数中有绑定(bind)(我不推荐)所以你可以只写改变这个

new Vivus("foo", {duration: 100, file: 'bar'}, myCallback.bind(this));

对此

new Vivus("foo", {duration: 100, file: 'bar'}, this.myCallback);

或者你可以跳过构造函数中的绑定(bind)并使用这个

new Vivus("foo", {duration: 100, file: 'bar'}, this.myCallback.bind(this));

或者你可以跳过构造函数中的绑定(bind)并使用箭头函数(我个人的建议)

new Vivus("foo", {duration: 100, file: 'bar'}, ()=> myCallback())

如果回调需要接受一个参数

new Vivus("foo", {duration: 100, file: 'bar'}, x=> myCallback(x))

或者如果回调需要接受可变数量的参数

new Vivus("foo", {duration: 100, file: 'bar'}, (...args)=> myCallback(...args))

有足够的选择吗?

^_^


同样,我建议在构造函数中删除对 this.onScroll 的绑定(bind)以及您拥有 this 的位置

componentDidMount() {
document.addEventListener('scroll', this.onScroll);
}

改用这个

componentDidMount() {
document.addEventListener('scroll', event=> this.onScroll(event));
}

关于javascript - ReactJS - Uncaught ReferenceError : function is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38131627/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com