我想要做的是从ListBox中选择一个项目并将其显示在同一个WebPage中。 ListBox正确呈现,但是当我尝试输出所选值时,它显示目标未定义。请参阅代码中的注释。
我尝试使用event.target.value来检索到目前为止一直对我有用的选定值,但是它说event.target是未定义的,并且该值无法访问。
注意:我尝试将Grommet用于此应用程序的样式,“List”,“Box”,“ListItem”都是索环组件。
任何帮助都将受到高度赞赏。
import React, {Component} from "react";
import Box from "grommet/components/Box";
import List from "grommet/components/List";
import ListItem from "grommet/components/ListItem";
const lb = [];
class ListBox extends Component{
state = {
products: [ //Array of Products
"Product1",
"Product2",
"Product3"
],
selected: null //State Variable where selected item will be stored
};
contents () {
for (let i = 0; i < this.state.products.length; ++i){
lb[i] =
<ListItem justify = "between" key = {i}>
<span>
{this.state.products[i]}
</span>
</ListItem>
}
}
itemSelected (event) {
console.log(event.target); //SHOWS TARGET UNDEFINED in Console Window
let temp = {
selected: event.target
}
this.setState(temp);
}
render () {
this.contents();
return (
<Box>
<List
selectable={true}
onSelect = { //The function call on selecting an item
(event) => {
this.itemSelected(event);
}
} >
{lb}
</List>
<p>Selected Product : {this.state.selected}</p>
</Box>
);
}
}
export default ListBox;
答案 0 :(得分:0)
grommet为您提供所选项目索引而非事件。 请查看官方文件。
itemSelected (index) {
console.log(index);
let temp = {
selected: this.state.products[index]
}
this.setState(temp);
}