【问题标题】:React/ ESLint - JSX props should not use arrow functionsReact/ ESLint - JSX 道具不应该使用箭头函数
【发布时间】:2019-01-10 02:17:55
【问题描述】:

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

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 错误:

JSX 属性不应使用箭头函数

我不完全确定如何在不使用箭头函数或使用.bind() 的情况下实现这一点。我可以向按钮元素添加一个数据属性,然后将事件传递给changeLanguage 函数并使用 event.target() 获取属性,但这并不像是在 React 中应该采用的方式.

谁能告诉我正确的方法是什么?

【问题讨论】:

  • 如果可以,你为什么要使用规则no-bind
  • no-bind 是我继承的 es lint 配置的一部分。我相信它的最佳做法?

标签: javascript reactjs eslint


【解决方案1】:

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

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:

class LanguageDropdown extends Component {
  ...

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

  ...
}

还有几件事:

  • 你有一个错字 onCLick 应该是 onClick
  • 重复项需要密钥

【讨论】:

  • 似乎是唯一合乎逻辑的选择!感谢其他观点,只是试图发布最少的代码:)
【解决方案2】:

试试下面的代码。 这里我尝试将值带入状态,同样可以使用道具进行尝试。 类 LanguageDropdown 扩展组件 { 构造函数(道具){ 超级(道具); this.state = {语言:['泰卢固语','印地语','英语']}; // this.changeLanguage = this.changeLanguage.bind(this); }

  changeLanguage(event,lang){
    //event.preventDefault();
    console.log('change lang: '+JSON.stringify(lang));
  };

  render() {
    return (
      <div>
        {this.state.languages.map(lang => <button onClick={(event)=>this.changeLanguage(event,lang)}>{lang}</button>)}
      </div>
    )
  }
}


render(<LanguageDropdown />, document.getElementById('root'));

when you bind the handler in the onClick event where you are passing the value to the handler, then we have to pass that value from the event and collect it to get that value.

【讨论】:

    猜你喜欢
    • 2021-05-14
    • 2017-05-25
    • 2023-03-12
    • 2017-09-13
    • 2018-11-24
    • 2018-10-07
    • 2020-07-30
    • 2022-09-27
    相关资源
    最近更新 更多