Unexpected use of 'event' no-restricted-gl

2019-04-28 19:33发布

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'))

2条回答
祖国的老花朵
2楼-- · 2019-04-28 19:46

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

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)
}
查看更多
▲ chillily
3楼-- · 2019-04-28 19:51

You might need to specify the event on the passing function I guess.

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

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

Try this if it works for you.

查看更多
登录 后发表回答