javascript - 无法将方法的头部传递给 React 标记中的事件处理

标签 javascript reactjs typescript events event-handling

在我的render()中,我有以下具有事件处理功能的组件。

render() { ...
  <input type="text" 
         onChange={(_) => { this.restate("email", _.target.value); }} />
}

private restate(type: string, input: any) { ...
  if (type === "email")
    this.setState({ ... });
}

它的工作原理和行为都符合预期。由于我现在正在学习 React,所以我尝试改进我的语法,使其看起来更流畅。我找到了this answer并喜欢事件处理程序分配的简洁性。因此,我更改了渲染并实现了要传递的处理程序,如下所示。

render() { ...
  <input type="text" onChange={ this.handleEmail } />
}

private handleEmail(data: React.ChangeEvent<HTMLInputElement>) {
  console.log("hit before: " + data.target.value);
  console.log(this);
  this.restate("email", data.target.value);
}

标记中的更改似乎有效,因为调用了方法handleEmail(...)。但是,我收到一条错误消息,指出 restate(...) 不是 undefined 的方法,事实上,当我调查 this 时> 是的,我发现它未定义

我需要帮助了解我做错了什么以及它如何偏离上面链接的文章。我尝试用 google 搜索 React 版本之间的语法差异,但一无所获。而且我不确定如何用正确的技术术语描述该问题。

最佳答案

我认为你应该做的是

render() { ...
  <input type="text" onChange={(e) => this.handleEmail(e) } />
}

我认为你的重述方法不是undefined方法的原因是因为你的方法没有绑定(bind)到组件。为了使您的方法成为 react 类的一部分,您需要将该方法绑定(bind)到该类。有几种方法可以做到这一点。在这样的类构造函数中:

 constructor(props) {
  super(props);
  this.handleEmail = this.handleEmail.bind(this);
 }

或者内部渲染函数,就像我上面展示的那样。第三种是在类体内使用箭头函数,如下所示:

handleEmail = () => {
  // call this function from render 
  // and this.whatever in here works fine.
};

关于javascript - 无法将方法的头部传递给 React 标记中的事件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52467285/

相关文章:

reactjs - Kubernetes 不等待 reactjs 加载

javascript - 在 react 中创建受控输入

javascript - 如何限制Fullcalendar禁用过去几天的所有操作?

java - java小程序中的值传递

reactjs - React 未捕获类型错误 : cannot read property x of undefined

reactjs - npm 更新后 React 无状态组件损坏

javascript - 使用 Javascript/Typescript 将现有 JSON 重新格式化为新 JSON

typescript :如何为联合类型中的枚举添加类型保护?

php echo 上没有弹出 javascript 警报

javascript - Chart.js 中的水平轴标签