[英]How to display selected Listbox value in ReactJS from state
What I want to do is select an item from the ListBox and display it in the same WebPage. 我要做的是从ListBox中选择一个项目,并将其显示在同一WebPage中。 The ListBox renders correctly, but when I try to Output the selected value, it shows target undefined.
ListBox可以正确呈现,但是当我尝试输出选定的值时,它会显示未定义的目标。 Refer comments in code.
请参考代码中的注释。
I tried using event.target.value to retrieve the value selected which has always worked for me so far, but it says event.target is undefined and the value is inaccessible. 我尝试使用event.target.value检索到目前为止对我一直有用的所选值,但是它说event.target是未定义的并且该值不可访问。
Note : I tried using Grommet for this app for styling, "List", "Box", "ListItem" are all grommet components. 注意:我尝试为此应用程序使用Grommet进行样式设置,“列表”,“框”,“ ListItem”都是索环组件。
Any help will be highly appreciated. 任何帮助将不胜感激。
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;
grommet give you selected item index not event. 索环给您选择的项目索引不是事件。 please check official document.
请检查正式文件。
http://grommet.io/docs/list http://grommet.io/docs/list
itemSelected (index) {
console.log(index);
let temp = {
selected: this.state.products[index]
}
this.setState(temp);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.