【问题标题】:onClick not working React jsonClick 不工作反应 js
【发布时间】:2016-07-15 17:22:07
【问题描述】:

我试图在用户单击 div 时调用一个函数(在反应中使用 onClick)。我现在不需要传递任何参数,只需要调用函数即可。我对 react.js 还很陌生,所以提前为我的无知道歉。谢谢。

var Test = React.createClass({

btnTapped: function(){
    console.log('tapped!');
},
render: function() {
    var stationComponents = this.props.stations.map(function(station, index) {

    return <div onClick={btnTapped()}><img src="img/test.png" />{station}</div>;

    });
    return <div>{stationComponents}</div>;
   }
});

var cards = ["amazon", "aeo", "aerie", "barnes", "bloomingdales", "bbw","bestbuy", "regal", "cvs", "ebay", "gyft", "itunes", "jcp", "panera", "staples", "walmart", "target", "sephora", "walgreens", "starbucks"];

ReactDOM.render(<Test stations={cards} />, document.getElementById('test-div'));

【问题讨论】:

  • 试试:onClick={this.btnTapped.bind(this)}
  • this.btnTapped() 是 this.btnTapped 的返回值,你要写不带括号的写

标签: javascript reactjs


【解决方案1】:

如果您的构建系统支持 babel,请在您的反应代码中使用 ES6 箭头函数。

如果您使用 ES6 类来创建组件,请在构造函数级别使用方法绑定以避免在每次渲染调用时进行绑定,并在 map 函数中提供 div 标签的键。

class Test extends React.Component {
    constructor(props) {
        super(props);
        this.btnTapped = this
            .btnTapped
            .bind(this);
    }
    btnTapped() {
        console.log('tapped');
    }
    render() {

        return (
            <div>
                {this
                    .props
                    .stations
                    .map((station, index) => {
                        return <div key={index} onClick={this.btnTapped}>{station}</div>
                    })
                }
            </div>
        )
    }
}

var cards = ["amazon", "aeo", "aerie", "barnes", "bloomingdales", "bbw", "bestbuy", "regal", "cvs", "ebay", "gyft", "itunes", "jcp", "panera", "staples", "walmart", "target", "sephora", "walgreens", "starbucks"];

    
ReactDOM.render(
    <Test stations={cards}/>, document.getElementById('test-div'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<body>
  <div id="test-div"></div>
</body>

【讨论】:

    【解决方案2】:

    您应该将函数设置为onClick 属性,而不是调用它。 应该是:onClick={this.btnTapped} 而不是 onClick={btnTapped()}

    另外,也可以这样做:

    <div 
      onClick={function(e) {
        this.btnTapped(); //can pass arguments this.btnTapped(foo, bar);          
      }}
     >
    

    当您需要将参数传递给您的函数时,通常会使用它。

    另外,为了能够从外部函数获取组件的上下文,你应该使用bind(this) 方法。喜欢:onClick={btnTapped.bind(this)}

    由于您使用范围函数来映射数组,因此会在以下位置创建新上下文:this.props.stations.map(function(station, index){}。并且this 被覆盖。只需使用 arrow function 代替:

    var stationComponents = this.props.stations.map((station, index) => {
    
       return <div onClick={this.btnTapped}><img src="img/test.png" />{station}</div>;
    
    });
    

    【讨论】:

    • 我仍然收到此错误:embedded:29 Uncaught TypeError: Cannot read property 'btnTapped' of null
    • 注意,如果不能支持粗箭头,可以将上下文绑定到map函数.map(function(..) {}.bind(this))
    • idk 为什么这个工作但 ()=> {...} 不 >.>
    【解决方案3】:

    注意:不是 reactjs 专家 :)

    我现在正在探索 reactjs,从 version 16.3.1 开始,箭头函数对我有用

    <button
        onClick={() => { console.log("button clicked");}}>
        button  
    </button>
    

    【讨论】:

      【解决方案4】:

      这有点像一个菜鸟的建议,但请检查你的 onClick() 函数的拼写,我拼错了像 onclick() 这样我花了很多时间一个小时才能找到它。

      【讨论】:

      • 这个问题已经有一个公认的答案,所以这不是一个真正有用的建议,如果将它放在 cmets 中可能更合适
      • @Anonymous 为了公平起见,你不能在声望达到 50 之前发表评论。 Shashi Shekhar 如果您不想受到声誉惩罚,我建议您简单地删除您的答案。如果您认为相关,您可以发布一个新的,考虑 Anonymou 的反馈。祝你在stackoverflow上好运! :)
      • 不,我会留下答案。
      【解决方案5】:

      您在函数之前错过了this 关键字。你也必须提供函数但不能调用它

      &lt;div onClick={this.btnTapped}&gt;

      更新:

      您错过了在地图回调函数中重新定义this

      使用箭头函数

      this.props.stations.map((station, index) => {
        return <div onClick={this.btnTapped}><img src="img/test.png" />{station}</div>;
      });
      

      或将上下文绑定到函数

      this.props.stations.map(function (station, index) {
        return <div onClick={this.btnTapped}><img src="img/test.png" />{station}</div>;
      }.bind(this));
      

      【讨论】:

      • 这似乎根本不起作用...该函数没有被调用,因此消息也没有记录到控制台。未捕获的类型错误:无法读取 null 的属性“btnTapped”
      【解决方案6】:

      当你想在渲染方法中使用一个函数时,首先你需要在构造函数中绑定这些方法。另一件事是,当您不想将任何参数传递给需要调用的方法时,请使用 onClick = {this.btnTapped} 而不是 onClick = {this.btnTapped()}。谢谢。

      import React, {Component} from 'react';
      import ReactDOM from 'react-dom';
      
      export default class Test extends Component {
      constructor (props) {
          super(props);
      //set cards value in state then you don't need to use props...
          this.state = {
              cards: ["amazon", "aeo", "aerie", "barnes", "bloomingdales", 
              "bbw","bestbuy", "regal", "cvs", "ebay", "gyft", "itunes", 
              "jcp", "panera", "staples", "walmart", "target", "sephora", 
              "walgreens", "starbucks"]
          }
          this.btnTapped = this.btnTapped.bind(this);
          // bind all the methods which you're using the "this.state" inside it....
      }
      
      btnTapped (card) {
          console.log("Coming here:::" + card)
      }
      
      render() {
          var cards = this.state.cards
          return (
              <div>
                  {/* if you don't want to pass an arguments use this... */}
                  {
                      cards.map((card, i) => 
                          <button key = {i} onClick = {this.btnTapped}>{card}</button>
                      )
                  }
                  {/* if you want to pass arguments use this  */}
                  {
                      cards.map((card, i) =>
                          <button key = {i} onClick = {(e) => this.btnTapped(card)}>{card}</button>
                      )
                  }
              </div>
          );
      }
      }
      ReactDOM.render(<Test />, document.getElementById('test-div'));
      

      【讨论】:

        【解决方案7】:

        对于问题未通过此线程的答案解决的人,只需我的 2 美分。我遇到了类似的问题,调试后我发现我的按钮的“z-index”为-9999,所以它位于图层后面,因此点击没有到达它。我将 z-index 更改为正值 1,然后点击被捕获。

        【讨论】:

          【解决方案8】:

          对于那些面临这个问题的人来说,它也可能是由于一些 CSS 问题而发生的

          对我来说,它是通过删除名为“pointer-events”的 CSS 属性来实现的。在我的 CSS 中,它被设置为 none。即

          pointer-events: none;

          我刚刚从我的 CSS 中删除了它,点击事件开始在 React 中工作!

          【讨论】:

            【解决方案9】:

            这是一个旧帖子,仍然发布我的答案,因为我遇到了同样的问题 2021 年,上述答案均无济于事。

            我在index.html 文件中添加了bundle.jshtml-webpack-plugin 也为我添加了它。 加载bundle.js 两次似乎导致了这个问题。从 index.html 中删除该引用后,它工作正常

            【讨论】:

              【解决方案10】:

              同样的错误发生在我身上,我发现错误是我两次导入 app.js

              【讨论】:

                【解决方案11】:

                如果您使用的是 webpack,请确保您在 webpack.config.js 中配置的输出文件(通常是 bundle.js)没有添加到 index.html 文件中。

                这解决了我的问题。

                【讨论】:

                  猜你喜欢
                  • 2016-01-06
                  • 1970-01-01
                  • 2020-10-15
                  • 2022-01-21
                  • 2021-03-02
                  • 1970-01-01
                  • 2017-10-25
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多