我正在创建一个简单的反应程序,我创建了一个语言数组并将其映射到创建列表项,当用户点击语言列表项时,它应该调用updateLanguage方法并相应地更新状态但是我收到错误。任何人都可以帮我解决问题。
code ::
import React, { Component } from 'react';
class Popular extends React.Component {
state = {
selectedLanguage: 'All'
};
updateLanguage() {
this.setState(lang => ({
selectedLanguage: lang
}));
}
render() {
const languages = ['All', 'JavaScript', 'Ruby', 'Java', 'CSS', 'Python'];
console.log();
return (
<div>
<ul className = 'languages'>
<p> Selected Language: {this.state.selectedLanguage} </p>
{languages.map((lang) => {
return (
<li
onClick={this.updateLanguage}
key={lang}>
{lang}
</li>
)
})}
</ul>
</div>
);
}
}
export default Popular;
错误::
答案 0 :(得分:1)
您必须进行以下更改:
更新以下代码:
import React, { Component } from 'react';
class Popular extends React.Component {
constructor() {
super();
this.state = {
selectedLanguage: 'All'
};
this.updateLanguage = this.updateLanguage.bind(this);
}
updateLanguage(lang) {
this.setState({ selectedLanguage: lang })
}
render() {
let languages = ['All', 'JavaScript', 'Ruby', 'Java', 'CSS', 'Python'];
return (
<div>
<ul className = 'languages'>
<p> Selected Language: {this.state.selectedLanguage} </p>
{languages.map((lang) => {
return (
<li
onClick={this.updateLanguage}
key={lang}>
{lang}
</li>
)
})}
</ul>
</div>
);
}
}
export default Popular;