【问题标题】:React.js function not firingReact.js 函数未触发
【发布时间】:2023-04-01 18:06:06
【问题描述】:

我最近看到我的一个项目弹出一个警告,说 React.createClass 现在已被弃用,因此我正在检查一些代码以使其与新建议兼容。

我遇到的一件事是我的一个函数似乎不像以前那样触发了。

class Example extends React.Component {

    constructor() {

        super();
        this.state = { content: "Initialize" }

    }

    changeScreen(newScreen) {

        // this fires
        alert("fired 01");

        // this function does not
        this.testFunc;

        var screen = "";

        switch(newScreen) {
            case "one":
                screen = "var01";
                break;
            case "two":
                screen = "var02";
                break;
            default:
                screen = "failed";
                break;
        }

    }

    testFunc() {
        alert("fired 02");
    }

    render() {

        return (
            <div>
                <External.Element execChangeScreen={this.changeScreen} />
                {this.state.content}
            </div>
        );

    }

}

ReactDOM.render (
    <Example />,
    document.getElementById("app")
);

我似乎无法触发 testFunc,我尝试如下调用

this.testFunc();
this.testFunc;
() => this.testFunc();

我不知道为什么,但我认为这可能与此有关

更新

以下所有答案都是正确的,我标记为已接受的答案对我来说似乎最清楚,但感谢大家的帮助

【问题讨论】:

  • this.testFunc() 是调用函数的正确方法。 this.testFunc 只是对函数的引用。 () => this.testFunc() 正在定义一个新函数。

标签: javascript jquery node.js reactjs


【解决方案1】:

您需要使用箭头函数语法在正确的范围内执行changeScreen()

<External.Element execChangeScreen={() => this.changeScreen('one')} />

并且在changeScreen()函数内部,确保正确调用testFunc。

changeScreen(newScreen) {

    // this fires
    alert("fired 01");

    // this function does not
    this.testFunc();
    ...
}

【讨论】:

    【解决方案2】:

    您必须在changeScreen 内显式设置this

    所以用

    <External.Element execChangeScreen={this.changeScreen.bind(this)} />
    

    而不是

    <External.Element execChangeScreen={this.changeScreen} />
    

    并调用你的函数

    this.testFunc();
    

    【讨论】:

      【解决方案3】:

      现在您没有使用React.createClass,您不再有this 自动为您绑定。问题出在调用this.changeScreen 的地方。

      对代码的最简单更改是在构造函数中绑定它:

      this.changeScreen = this.changeScreen.bind(this);
      

      然后确保您确实在调用您的函数:

      this.testFunc();
      

      如果您改为在渲染方法中编写 this.changeScreen.bind(this),则每次渲染组件时都会创建一个新的函数副本。

      【讨论】:

        【解决方案4】:

        试试 testFunc = () => {} 或者像 this.testFunc = this.testFunc.bind(this) 这样的构造方法绑定它

        【讨论】:

          猜你喜欢
          • 2021-06-15
          • 2021-05-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多