反应 ― 显示字段但获取对象

React — display field but get object

本文关键字:获取 取对象 字段 显示 反应      更新时间:2023-09-26

我有一个对象Category,它有两个字段:namedescription

我想显示一个下拉列表,其中向用户显示所有类别的description。但是,描述不是唯一的,所以我想获取用户选择的对象而不是其描述。

我想做这样的事情:

handleSelect: function(event){
   // Here, I would like to get the Category selected, not the description!!!
},
render: function(){
    var categoryDesc = this.props.categories.map(function(elem){
        return <option><a href="#">{elem.description}</a></option>
    });
    return(
        <div>
            <p>Select category</p>
            <div class="dropdown">
                <select class="form-control" onChange={this.handleSelect}>
                    {categoryDesc}
                </select>
            </div>
        </div>
    )
}

如果您在map中使用index,则可以将其保存为每个option的值,然后使用它从props.categories获取正确的项目。

我认为您正在寻找这样的东西:

handleSelect: function(index){
    console.log(this.props.categories[index]); // element with name and description
},
render: function(){
    var categoryDesc = this.props.categories.map(function(elem, index){
        return (
            <option class="form-control" value={index}>
                {elem.description}
            </option>
        );
    });
    return(
        <div>
            <p>Select category</p>
            <select onChange={this.handleSelect}>
                {categoryDesc}
            </select>
        </div>
    );
}