使用event.target.id从bind获取id时,意外使用'event'无限制全局变量 [英] Unexpected use of 'event' no-restricted-globals when using event.target.id to get id from bind(this)

查看:628
本文介绍了使用event.target.id从bind获取id时,意外使用'event'无限制全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码适用于Codepen:请参阅 https://codepen.io/pkshreeman/pen / YQNPKB?editors = 0010 但是我试图在我自己的'create-react-app'中使用它,'no-restricted-globals'的错误由 event.target触发.ID 。什么是解决方法。除了使用事件目标之外,你如何从'this'得到id?

This code works on Codepen: See https://codepen.io/pkshreeman/pen/YQNPKB?editors=0010 However I am trying to use this in my own 'create-react-app' and the error of 'no-restricted-globals' is trigged by event.target.id. What is a workaround for this. How do you get id from 'this' in react other than using the event target?

const Elem = (props) =>{ 
  return (<div>
    <h1 onClick={props.clickon} id="GM"> Good Morning! 
      <br/> 
      {props.name} {props.last} 
      <br />
      This is phase three</h1>
    <button id="btn1" onClick={props.clickon}> {props.text} </button>
      <button id="btn2" onClick={props.clickon}> Second Button </button>
      </div>
  );
};



class App extends React.Component{
  constructor(props) {
   super(props);
   this.handleClick = this.handleClick.bind(this);
 }

handleClick(){  
  var clickedId = event.target.id;
    console.log(clickedId);
  alert("It works! You clicked " + clickedId)
}
  render(){
    return (
    <Elem name = 'paul' last='shreeman' clickon={this.handleClick} text='PushMe'/>
  )
}
}

ReactDOM.render(
<App />, document.getElementById('root'))


推荐答案

奇怪的是,这甚至可以在codepen中运行 - 看起来你正在使用全局事件属性。

It's strange that this even works in codepen -- it looks like you're using a global event property.

正确的方法是从 handleClick 函数的第一个参数中获取事件对象:

The right way to do this is to get the event object from the handleClick function's first param:

handleClick(event) {  
  var clickedId = event.target.id;
  console.log(clickedId);
  alert("It works! You clicked " + clickedId)
}

这篇关于使用event.target.id从bind获取id时,意外使用'event'无限制全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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