javascript - 在事件处理程序中访问 React 组件参数

标签 javascript reactjs

我不确定这是否是最好的方法,但我正在尝试在 onMouseOver 事件处理程序中访问 React 组件的参数。

事件处理器:

  handleTabHover = event => {
    this.setState({ indicatorColor: event });
  };

react 组件:

  <LinkTab
    label="Dashboard"
    to="/"
    indicatorColor="gray"
    onMouseOver={this.handleTabHover}
    onFocus={this.handleTabHover}
  />

基本上,我希望 handleTabHover 函数中的 event 成为 LinkTab 组件,然后我可以访问它的“indicatorColor”参数来设置类 indicatorColor 状态,但事实并非如此。我是 React 和 ES6 语法的新手,所以我确信我遗漏了一些关于事件处理程序参数如何工作的基础知识。

最佳答案

Basically, I'm expecting that "event" in the handleTabHover function to be the "LinkTab" component and then I can access it's "indicatorColor" param to set the class "indicatorColor" state, but that's not the case.

是的,你不能那样做。

正确的做法是

<LinkTab
  label="Dashboard"
  to="/"
  indicatorColor={Colors.Deloitte.Primary.coolGray2}
  onMouseOver={() => this.handleTabHover(Colors.Deloitte.Primary.coolGray2)}
  onFocus={this.handleTabHover}
/>

并且在您的处理程序中将是

handleTabHover = indicatorColor => {
    this.setState({ indicatorColor });
};

您可以在此处阅读更多内容。 https://reactjs.org/docs/faq-functions.html#how-do-i-pass-a-parameter-to-an-event-handler-or-callback

关于javascript - 在事件处理程序中访问 React 组件参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53451002/

相关文章:

javascript - ExtJs 5.0 : forEach on Array of Objects not working in IE8

javascript - 提交表单会触发一个 ajax 调用,该调用会在成功时发布到操作页面

javascript - Stripe 表单返回丢失的参数

css - 覆盖一些material-ui类样式但保留默认样式

javascript - 尝试使用自定义内容创建 React 抽屉导航

javascript - React Native Paper ProgressBar 不可见

javascript - AngularJS 未捕获语法错误 : Unexpected token :

javascript - 为什么我要在要循环的数组之外获取返回元素?

javascript - 如何重用 Yup 验证模式 + 声纳扫描在 yup 模式验证文件上显示更多重复,它增加了重复覆盖率

reactjs - NavLink onActive 回调