我从json填充了一个Material UI子菜单。保存此子菜单数组的主菜单项将根据所选内容进行更改。见下图
保存子菜单的主菜单项如下所示
<MenuItem
primaryText={this.state.selectedLanguage.name}
rightIcon={<ArrowDropRight />}
style={{userMenuItem}}
leftIcon={
<img className="flag" src={this.state.selectedLanguage.icon}/>
}
menuItems={languageMenu} //see below
/>
嵌套菜单来自这里
const languageMenu =
<div>
{languages.map((item, index) => (
<MenuItem
key={index}
onClick={this.onLanguageChange}
primaryText={languages[index].name}
style={{userMenuItem}}
leftIcon={
<img className="flag" src={languages[index].icon}/>
}/>
))}
</div>
最终,数据存储在像这样的json中
const languages = [
{
name: 'English',
icon: './assets/images/flags/uk.png',
link: ''
},
{
name: 'Español',
icon: './assets/images/flags/Spain.png',
link: ''
},
{
name: 'Français',
icon: './assets/images/flags/France.png',
link: ''
}
...
];
由于对React的理解不足,我在构造函数状态中为选定语言创建了一个初始值
constructor(props) {
super(props);
this.state = {
selectedLanguage:{
name:"English",
icon:"./assets/images/flags/uk.png",
},
}
}
和一个将处理变化的函数(这是我的问题区域,我敢肯定)
onLanguageChange = () => this.setState(
{
selectedLanguage: this.state.selectedLanguage.name,
}
);
我需要正确构建此onChange()
函数,以根据单击的子菜单更改状态。这将为我提供构建其他属性的基础,这些属性将触发点击上的翻译功能
任何帮助将不胜感激。感谢
答案 0 :(得分:1)
该操作需要一个参数 - 新语言:
onLanguageChange = languageName => this.setState({
selectedLanguage: languageName
});
您需要从onClick
传递
{languages.map((language, index) => (
<MenuItem
key={index}
onClick={() => this.onLanguageChange(language.name)}
primaryText={language.name}
style={{userMenuItem}}
leftIcon={
<img className="flag" src={language.icon}/>
}
/>
))}
我不确定您是要将language
存储在您的州还是name
。两种方式都有其用途。
答案 1 :(得分:1)
像这样的东西
const languages = [...]
constructor(props) {
super(props);
this.state = {
selectedLanguage: 0
}
}
onLanguageChange = (index) => this.setState({ selectedLanguage: index });
const mainMenu =
<MenuItem
primaryText={languages[this.state.selectedLanguage].name}
rightIcon={<ArrowDropRight />}
style={{userMenuItem}}
leftIcon={
<img className="flag" src={languages[this.state.selectedLanguage].icon}/>
}
menuItems={languageMenu} //see below
/>
const languageMenu =
<div>
{languages.map((item, index) => (
<MenuItem
key={index}
onClick={this.onLanguageChange(index)}
primaryText={languages[index].name}
style={{userMenuItem}}
leftIcon={
<img className="flag" src={languages[index].icon}/>
}/>
))}
</div>