简体   繁体   中英

Do I need to bind event handlers to `this` with TypeScript + React?

I have a component with a simple button handler method. If I don't bind the onClick handler to this in the constructor (or inline on the onClick itself), then I get an error because the context of the handleAdd method is not the instance where my component's state is...

I understand how the bind works, but is there a workaround to avoid having to use bind all over the place with TypeScript + React?

export class TodoList extends React.Component<ITodoListProps, Partial<ITodoListState>> {
    constructor(props: ITodoListProps) {
        super(props);
        this.state = { items: props.items };

        this.handleAdd.bind(this);
    }

    public render() {
        return (
            <div>
                <button onClick={this.handleAdd}>Add</button>
                <ul>
                    {this.state.items.map((todo, i) => {
                        return <TodoItem key={i} name={todo.name} />
                    })}
                </ul>
            </div>
        );
    }

    handleAdd(e: any) {
        this.setState({
            items: [...this.state.items, { name: "foo" }]
        });
    }
}

but is there a workaround to avoid having to use bind all over the place with TypeScript + React?

Yes. Use an arrow function:

handleAdd = (e: any) => {
    this.setState({
        items: [...this.state.items, { name: "foo" }]
    });
}

More

The arrow function works for anonym functions but reduces the extensibility of the class (if you want to extend that class and redefine the function but using super).

To call the function being a member of the class the easy way is use bind.

Is worst use bind than use anonym functions?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM