我目前正在用 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 props should not use arrow functions
我不完全确定如何在不使用箭头函数或使用 .bind()
的情况下实现这一点。我可以向按钮元素添加一个数据属性,然后将事件传递给 changeLanguage
函数并使用 event.target() 获取属性,但这并不像它的方式应该在 React 中处理。
谁能告诉我正确的方法是什么?
最佳答案
您可以将按钮重构为它自己的组件:
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
- 您需要一个 key 来处理重复的项目
关于javascript - React/ESLint - JSX 属性不应该使用箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51651425/