使用ReactJS

时间:2018-11-16 04:16:26

标签: html reactjs

我目前正在使用多个选择选项,我对如何突出显示数据库中的值有疑问。我有setState 获取商店的商店类型

输出应该像这样

Ouput

我的api存储类型的响应 Response API

componentDidMount() {
    const id = this.props.match.params.id;
    axios.get('/api/get_update_store_data/'+ id).then(response => {
        this.setState({

            store_type:response.data[0].store_type,

        })
    }).catch(error => console.log(error.response));
}

我有把柄

handleStoreType(e){
    var options = e.target.options;
    var value = [];
    for (var i = 0, l = options.length; i < l; i++) {
        if (options[i].selected) {
            value.push(options[i].value);
        }
    }
    this.setState({store_type: value});
}

JSX文件

<label>Store Type</label>
<select onChange={this.handleStoreType} value={this.state.store_type} multiple name="selectedOption" required="" className="form-control">
    <option selected>Choose your option</option>
    <option value="Dine-in">Dine-in</option>
    <option value="Take-out">Take-out</option>
    <option value="Home Delivery">Home Delivery</option>
    <option value="Drive Thru">Drive Thru</option>
</select>

2 个答案:

答案 0 :(得分:1)

根据您共享的内容,response.data[0].store_type来自服务器,是字符串而不是字符串数组。它必须是一个与value<option>元素的<select>属性的componentDidMount() { const id = this.props.match.params.id; axios.get('/api/get_update_store_data/'+ id) .then(response => { this.setState({ store_type: response.data[0].store_type.split(',') }) }) .catch(error => console.log(error.response)); } 属性完全匹配的字符串数组。使用String.prototype.split()尝试以下操作,将字符串转换为字符串数组,并以逗号分隔:

package com.ashwin.springsecurityangular.model;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
@Table(name = "letter_doc")
public class LetterDoc implements Serializable {

    private static final long serialVersionUID = 1L;

    @ManyToOne(fetch = FetchType.EAGER, optional = false,cascade=CascadeType.PERSIST)
    @JoinColumn(name = "letterNo")
    @JsonIgnore
    private Letter letter;

    @ManyToOne(fetch = FetchType.EAGER, optional = false,cascade=CascadeType.PERSIST)
    @JoinColumn(name = "documentId")
    @JsonIgnore
    private Document document;

    private String docFile;

//i omitted getters and setters and both constructor
}

希望有帮助!

答案 1 :(得分:0)

您可以在JSX / HTML中完成

<option value="Dine-in"><mark>Dine-in</mark></option>
<!-- Other options -->
<option value="Drive Thru"><mark>Drive Thru</mark></option>