【问题标题】:Do I need to bind event handlers to `this` with TypeScript + React?我是否需要使用 TypeScript + React 将事件处理程序绑定到`this`?
【发布时间】:2017-05-16 00:18:11
【问题描述】:

我有一个带有简单按钮处理程序方法的组件。如果我没有将onClick 处理程序绑定到构造函数中的this(或内联onClick 本身),那么我会收到一个错误,因为handleAdd 方法的上下文不是我的组件所在的实例状态是...

我了解bind 的工作原理,但是否有一种解决方法可以避免在 TypeScript + React 中到处使用bind

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" }]
        });
    }
}

【问题讨论】:

  • 为什么有人反对这些?请发表评论,以便我们提高质量。
  • 就像 YouTube - 总有反对票 - 无论如何。

标签: javascript reactjs typescript


【解决方案1】:

但是有没有一种解决方法可以避免在 TypeScript + React 中到处使用 bind?

是的。使用箭头函数:

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

更多

【讨论】:

    【解决方案2】:

    箭头函数适用于匿名函数,但会降低类的可扩展性(如果您想扩展该类并重新定义函数但使用 super)。

    要调用作为类成员的函数,最简单的方法是使用绑定。

    使用绑定比使用匿名函数最糟糕吗?

    【讨论】:

      猜你喜欢
      • 2017-03-19
      • 2017-06-14
      • 1970-01-01
      • 2015-06-26
      • 2017-10-25
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多