CusineList每次点击都打印0。无法在li标签中获取值。
我尝试将cussine传递给我的updateMenu,但是输出不正确。当我单击All All时,它会打印阿拉伯语。
这是我的代码
class Menu extends Component {
state={
cusineList: "All"
}
updateMenu = (e) => {
this.setState( {cusineList: e.target.value} );
console.log(this.state.cusineList);
}
render() {
const cusineArray = ["All",
"Arabian",
"Continental",
"Italian",
"Indian"];
let cusines = (
<ul className="cusine-list">
{ cusineArray.map(cusine =>
li key={cusine} onClick={(e)=>this.updateMenu(e)}>
{cusine}
</li>
)}
</ul>
);
return (
<div>{cusine}</div>
}
}
export default Menu;
我想根据点击的项目更新状态
答案 0 :(得分:1)
<li/>
标签没有value属性。使用
updateMenu = (e) => {
this.setState( {cusineList: e.target.innerHTML}, () => {
console.log(this.state.cusineList)
});
}
这里是slackblitz。 innerHTML将在<li>
标记内获取所有html +文本。另外,在这种情况下,您也可以按照{Kejt
textContent
答案 1 :(得分:0)
可以,因为li没有价值。尝试使用e.target.textContent
供参考-https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_node_textcontent
答案 2 :(得分:0)
this.setState()不同步,请尝试:
this.setState({ cusineList: e.target.value }, () => console.log(this.state.cusineList));
答案 3 :(得分:0)
看看这是否是您想要的:
class Menu extends React.Component {
constructor(props) {
super(props);
this.state={
cusineList: "All"
};
}
updateMenu = (selectedCusine) => {
console.log(selectedCusine + ' has been selected!');
this.setState( {cusineList: selectedCusine} );
};
render() {
const cusineArray = ["All",
"Arabian",
"Continental",
"Italian",
"Indian"
];
const cusineItems = cusineArray.map(cusine =>
<li key={cusine} className='cusineItem' onClick={()=>this.updateMenu(cusine)}>
{cusine}
</li>
);
return (
<div>
<ul className="cusine-list">
{cusineItems}
</ul>
<div>Selected cusine is: {this.state.cusineList}</div>
</div>
);
}
}
ReactDOM.render(<Menu/>, document.getElementById('root'));
.cusineItem {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>