Làm thế nào để tránh việc cần phải binding trong React?

{{FormatNumbertoThousand(model.total_like)}} lượt thích
594 lượt xem
Reactjs master

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>
    );
};
{{login.error}}