在组件上反应onClick事件 [英] React onClick event on component

查看:109
本文介绍了在组件上反应onClick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为< SensorList /> 的React组件,它有许多孩子< SensorItem /> (另一个React组件)。我想要从<$ c $内的每个< SensorItem /> 上声明一个 onClick 事件c>< SensorList /> 。我尝试过以下操作:

I have a React component called <SensorList /> that has many child <SensorItem />s (another React component). I want to be able to declare an onClick event on each <SensorItem /> from within <SensorList />. I have tried doing the following:

sensorSelected: function(sensor) {
    console.log('Clicked!');
},

render: function() {
    var nodes = this.state.sensors.map(function(sensor) {
        return (
            <SensorItem onClick={ this.sensorSelected } />
        );
    }.bind(this));

    return (
        <div className="sensor-list">
            { nodes }
        </div>
    );
}

不用说,我没有得到任何点击!来到我的控制台Chrome中的React检查器表示已注册 onClick 事件,并具有上述功能正文。

Needless to say, I do not get any "Clicked!" coming up in my console. The React inspector in Chrome indicates that an onClick event is registered, with the above function body as it should be.

因此,我得出结论,我不能在实际的< SensorItem /> 标签中注册 onClick 事件(我不知道为什么这是,但是)。

I conclude, therefore, that I can't register onClick events on the actual <SensorItem /> tags (I'm not sure why this is, however). How do I go about achieving this otherwise?

推荐答案

这取决于您的SensorItem组件的定义。
因为SensorItem不是原生DOM元素,而是像您所说的那样,另外一个React组件,这里定义的 onClick 只是该组件的一个属性。您需要做的是,SensorItem组件内部将onClick参数传递给DOM组件的onClick事件:

This depends on your SensorItem component's definition. Because SensorItem isn't a native DOM element but, like you said, another React component, onClick as defined here is simply a property of that component. What you need to do is, inside of the SensorItem component pass the onClick prop to an DOM component's onClick event:

var SensorItem = React.createClass({
  render: function() {
    return (
      <div className="SensorItem" onClick={this.props.onClick}>
       ...
      </div>
    );
  }
});

这篇关于在组件上反应onClick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆