Có một số cách tiếp cận phổ biến được sử dụng để tránh binding các phương thức trong React:
1. Định nghĩa Event handler của bạn dưới dạng một Arrow function
class SubmitButton extends React.Component {
constructor(props) {
super(props);
this.state = {
isFormSubmitted: false,
};
}
render() {
return (
<button
onClick={() => {
this.setState({ isFormSubmitted: true });
}}
>
Submit
</button>
);
}
}
2. Định nghĩa Event handler của bạn dưới dạng một Arrow function được gán cho một Class field
class SubmitButton extends React.Component {
state = {
isFormSubmitted: false,
};
handleSubmit = () => {
this.setState({
isFormSubmitted: true,
});
};
render() {
return <button onClick={this.handleSubmit}>Submit</button>;
}
}
3. Sử dụng một Function component với Hooks
const SubmitButton = () => {
const [isFormSubmitted, setIsFormSubmitted] = useState(false);
return (
<button
onClick={() => {
setIsFormSubmitted(true);
}}
>
Submit
</button>
);
};