Javascript 在组件上反应 onClick 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28268835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:31:12  来源:igfitidea点击:

React onClick event on component

javascripteventsreactjs

提问by GTF

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

我有一个名为的 React 组件<SensorList />,它有很多 child <SensorItem />(另一个 React 组件)。我希望能宣布一个onClick对每个事件<SensorItem />从内部<SensorList />。我尝试执行以下操作:

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>
    );
}

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

不用说,我没有得到任何“点击!” 出现在我的控制台中。Chrome 中的 React 检查器指示onClick注册了一个事件,上面的函数体应该是这样。

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

因此,我得出结论,我无法onClick在实际<SensorItem />标签上注册事件(但是,我不确定为什么会这样)。否则我如何实现这一目标?

回答by Bogdan Dumitru

This depends on your SensorItem component's definition. Because SensorItem isn't a native DOM elementbut, like you said, another React component, onClickas 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:

这取决于您的 SensorItem 组件的定义。因为 SensorItem 不是本机 DOM 元素,但正如您所说,另一个 React 组件,这里定义的onClick只是该组件的一个属性。您需要做的是,在 SensorItem 组件内部将 onClick 属性传递给 DOM 组件的 onClick 事件:

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