onClick
, onSubmit
, onHover
<!-- HTML Event Handler -->
<button onclick="handleData()">
Submit Data
</button>
/* React Event Handler */
<button onClick={handleData}>
Submit Data
</button>
event.preventDefault()
must be done in the handlerfunction Link () {
function handleClick(event) {
event.preventDefault();
doSomethingWithTarget(event);
}
return (
<a href="#" onClick={handleClick}>
Click Me React
</a>
);
}
Propery | Return Type |
---|---|
bubbles | boolean |
cancelable | boolean |
currentTarget | DOMEventTarget |
defaultPrevented | boolean |
eventPhase | number |
isTrusted | boolean |
nativeEvent | DOMEvent |
preventDefault() | void |
isDefaultPrevented() | boolean |
stopPropagation() | void |
isPropagationStopped() | boolean |
target | DOMEventTarget |
timeStamp | number |
type | string |
event.persist()
firstfunction onClick(event) {
console.log(event); // => nullified object.
console.log(event.type); // => "click"
const eventType = event.type; // => "click"
setTimeout(function() {
console.log(event.type); // => null
console.log(eventType); // => "click"
}, 0);
// Won't work.
// this.state.clickEvent will only contain null values.
this.setState({clickEvent: event});
// You can still export event properties.
this.setState({eventType: event.type});
}
bind
the this
in ES6 Classesbind
in the constructor, or use an ES6 Arrow Functionclass Toggle extends React.Component {
constructor (props) {
super(props);
this.state = { isToggleOn: true };
// Binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? true : false}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
this.function = this.function.bind(this)
are verbosecreate-react-app
or otherclass LoggingButton extends React.Component {
// This syntax ensures `this` is bound within handleClick.
// Warning: this is *experimental* syntax.
constructor (props) {
super(props)
this.state = { isToggleOn: true }
}
handleClick = () => {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? true : false}
</button>
);
}
}
Let's create a simple login page! Create a new React project that:
/