handleselectenquiryId(e) {
let attribute = document.getElementById(e.target.value);
let sectorattrribute = attribute.getAttribute("data-items");
this.setState({ enquiryId: e.target.value }, ()=>{
let data = {
id : sectorattrribute
}
UserAction._getSingleEnquiry(data);
});
}
handleselectBookingId(e) {
let attribute = document.getElementById(e.target.value);
let sectorattrribute = attribute.getAttribute("data-item");
console.log(sectorattrribute);
this.setState({ bookingId: e.target.value }, ()=>{
let data = {
id : sectorattrribute
}
UserAction._getSingleBooking(data);
});
}
<div className="col-sm-4 col-6">
<h2 className="card-inside-title">Enquiry Id</h2>
<select className="c-select form-control box_ip" onChange={this.handleselectenquiryId.bind(this)} value={this.state.enquiryId}>
<option value='-1' disabled>Select Enquiry</option>
{this.state.enquirieslist.enquiries.map((el) => <option id={el.enquiryId} data-items={el.id} value={el.enquiryId}>{el.enquiryId}</option>)}
</select>
</div>
<div className="col-sm-4 col-6">
<h2 className="card-inside-title">Booking Id</h2>
<select className="c-select form-control box_ip" onChange={this.handleselectBookingId.bind(this)} value={this.state.bookingId}>
<option value='-1' disabled>Select Booking</option>
{this.state.bookinglist.bookings.map((el) => <option id={el.bookingId} data-item={el.id} value={el.bookingId}>{el.bookingId}</option>)}
</select>
</div>
我有两个下拉菜单,两个选择标签的值分别为1和2。
我分别在 data-items和data-item属性中保持不变,因为el.id
的唯一性是handleselectBookingId
的onChange,它采用handleselectenquiryId
onchange的ID
我可以知道我在做什么错误。
在我处理document.getElementById时,这是工作的正确方法还是解决此问题的任何方法。
答案 0 :(得分:0)
在react中使用document.getElementById(e.target.value)不好,因为它具有访问DOM节点的引用。
您可以在这种情况下使用ref:
首先,将ref分配给您的选项:
<select className="c-select form-control box_ip" onChange=
{this.handleselectenquiryId.bind(this)} value={this.state.enquiryId}>
<option value='-1' disabled>Select Enquiry</option>
{this.state.enquirieslist.enquiries.map((el) => <option ref={val => this[el.enquiryId] = val} data-items={el.id} value={el.enquiryId}>{el.enquiryId}</option>)}
</select>
然后在您的onChange处理程序中访问其数据项属性值:
this[e.target.value].attributes['data-items'].value)