简体   繁体   中英

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. The ListBox renders correctly, but when I try to Output the selected value, it shows target undefined. 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.

Note : I tried using Grommet for this app for styling, "List", "Box", "ListItem" are all grommet components.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM