如何从状态显示 ReactJS 中选定的列表框值

How to display selected Listbox value in ReactJS from state

我想要做的是 select ListBox 中的一个项目并将其显示在同一个网页中。 ListBox 正确呈现,但是当我尝试输出 selected 值时,它显示目标未定义。参考代码中的注释。

我尝试使用 event.target.value 检索值 selected,到目前为止它一直对我有用,但它说 event.target 未定义并且该值不可访问。

注意:我尝试使用 Grommet 为这个应用程序设计样式,"List"、"Box"、"ListItem" 都是 grommet 组件。

非常感谢任何帮助。

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;

索环给你选择的项目索引不是事件。 请查看官方文档

http://grommet.io/docs/list

itemSelected (index) {
    console.log(index);  
    let temp = {
        selected: this.state.products[index]
    }
    this.setState(temp);
}