【问题标题】:Simple javascript in ReactJS component not working [duplicate]ReactJS组件中的简单javascript不起作用[重复]
【发布时间】:2021-01-16 10:12:39
【问题描述】:

这是我的组件:

import React, {Component} from 'react';
import 'D:/School/Alta/interactiveweb/src/webapp/src/App.css'

class Chat extends Component {

  test() {
    alert();
  }

  render() {
    return <nav onClick={this.test()} className={"menu"} id={"Chat"}>
        <div className={"menu-itemContainer"}>
            <div className={"menu-item"}>
                <img alt={""} className={"chatPF"} src={require('./Images/defaultPF.png')}/>
                <a className={"chatname"}>Test</a>
                <a className={"chatlastuser"} id={"chatlastuser"}>
                    <font color={"orange"}>Bram: </font>wow wtf...
                </a>
                <a className={"chatlasttime"}>20:28</a>
            </div>
        </div>
    </nav>;
  }
}

export default Chat;

启动时它会多次运行该功能,但是当它被加载并且我点击导航时它就不起作用了。

【问题讨论】:

  • 请不要上传images of code。它们不能被复制来重现问题,它们不能被未来的读者搜索,它们比文本更难阅读。请以文本形式发布实际代码以创建minimal reproducible example
  • 使用 onClick = {() => this.test()}
  • 更好:onClick={this.test}

标签: javascript reactjs components


【解决方案1】:

您可以在 React here 中了解有关事件的更多信息。话虽这么说,以下应该有效。每次渲染组件时您都在调用该函数,但您只想在单击发生时调用它。为此,您应该只传递将被触发的处理程序/方法。

import React, {Component} from 'react';
import 'D:/School/Alta/interactiveweb/src/webapp/src/App.css'

class Chat extends Component {
  test() {
    alert();
  }

  render() {
    return <nav onClick={this.test} className="menu" id="Chat">
        <div className="menu-itemContainer">
            <div className="menu-item">
                <img alt="" className="chatPF" src={require('./Images/defaultPF.png')}/>
                <a className="chatname">Test</a>
                <a className="chatlastuser" id="chatlastuser">
                    <font color="orange">Bram: </font>wow wtf...
                </a>
                <a className="chatlasttime">20:28</a>
            </div>
        </div>
    </nav>;
  }
}

export default Chat;

【讨论】:

  • 没有解释的答案没有那么有用。
  • 我正在编辑它。
【解决方案2】:

您需要使用onClick={this.test},而不是onClick={this.test()}。正如您所拥有的,它立即调用该函数并在 onClick 侦听器中未定义。通过按原样传递函数,您可以确保在单击元素时正确调用它。


虽然 onClick={()=&gt;this.test()} 可以工作,但它不必要地向调用堆栈添加了另一个函数,因为在 JavaScript 中函数是 first-class objects

【讨论】:

    【解决方案3】:

    将其更改为 onClick={this.test}onClick={()=&gt;this.test()}

    你不想调用属性中的函数,你只想声明它们。当点击事件发生时,它们将被调用。

    【讨论】:

    • 这个答案很好,但我不建议使用()=&gt;this.test(),因为它不必要地向调用堆栈添加了另一个函数。在 JS 中的函数是first-class objects
    猜你喜欢
    • 2012-06-07
    • 2017-12-08
    • 2016-03-02
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    相关资源
    最近更新 更多