React / ESLint-JSX道具不应该使用箭头功能 [英] React/ ESLint - JSX props should not use arrow functions

查看:119
本文介绍了React / ESLint-JSX道具不应该使用箭头功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在React中创建一个组件,并且正在使用ES Lint规则 react / jsx-no-bind 。我的问题是我希望能够将参数传递给组件函数。这是我想用来实现的代码:

I'm currently creating a component in react and i'm using the ES Lint rule react/jsx-no-bind. My issue here is that I want to be able to pass a parameter to my components function. Here is the code I would like to use to be able to do so:

class LanguageDropdown extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  changeLanguage = (lang) => {
    console.log(lang)
  };

  render() {
    return (
      <div>
        {this.props.languages.map(lang => <button onCLick={() => this.changeLanguage(lang)}>{lang}</button>)}
      </div>
    )
  }

...

这会拉高ESlint错误:

This pulls up the ESlint error:


JSX道具不应该使用箭头功能

JSX props should not use arrow functions

我不确定如何实现无需使用箭头功能或使用 .bind()。我可以将数据属性添加到button元素,然后将事件传递到 changeLanguage 函数中,并使用event.target()来获取属性,但这不是感觉这是在React中应该采用的方法。

I'm not entirely sure how to achieve this without using an arrow function or using .bind(). I could add a data-attribute to the button element and then just pass in the event into the changeLanguage function and fetch the attribute using event.target() but this doesn't feel like it's the way it should be approached in React.

有人可以告诉我正确的方法吗?

Can someone tell me what would be the correct way?

推荐答案

您可以将按钮重构为它自己的组件:

You can refactor button into its own component:

class MyButton extends Component {
  static propTypes = {
    language: PropTypes.string.isRequired,
  };

  onClick = () => console.log(this.props.language);

  render() {
    const {language} = this.props;
    return (
      <button onClick={this.onClick} type="submit">
        {language}
      </button>);
  }
}

然后在LanguageDropDown类中,使用MyButton这样:

and then in your LanguageDropDown class, use MyButton like this:

class LanguageDropdown extends Component {
  ...

  render() {
    return (
      <div>
        {this.props.languages.map(lang => <MyButton key={lang} language={lang}/>)}
      </div>
    )
  }

  ...
}

还有两件事:


  • 您有错字onCLick应该是onClick

  • 您需要重复项的密钥

这篇关于React / ESLint-JSX道具不应该使用箭头功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆