【发布时间】: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