此代码适用于 Codepen:请参阅https://codepen.io/pkshreeman/pen/YQNPKB?editors=0010 但是我试图在我自己的“create-react-app”和“no-restricted-”错误中使用它globals' 由 触发event.target.id
。什么是解决方法。除了使用事件目标之外,您如何从“this”中获取 id 以做出react?
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'))