好的,这里没有现有的解决方案,所以...
如何从React的数据列表中获取数据属性(不是从选择中获取)?
渲染JSX
<input list="list-id" id="input-id" multiple onChange={handleInputChange} />
<datalist id="list-id">
{
options.map((item,key) => {
return <option key={key} data-foo={item.id} value={item.value}>{item.name}</option>;
})
}
</datalist>
事件处理程序
function handleInputChange(e) {
console.dir(e.target.dataset) // Empty DOMStringMap
console.dir(e.target.getattribute('data-foo')) // null
console.dir(e.target.attributes) // NamedNodeMap with no option
console.dir(e.target.options) // undefined
}
我已经在其他vanilla JS案例中设法获得了这样的价值...
let inputvalue = document.getElementById("input-id").value;
let option = document.querySelector(`option[value="${inputvalue}"]`).getattribute('data-foo');
在React中会这样使用...
function getDatalistSelectedOption(inputId,attribute) {
let inputvalue = document.getElementById(inputId).value;
let option = document.querySelector(`option[value="${inputvalue}"]`);
let optionValue = option ? option.getattribute(attribute) : "";
return optionValue
}
// In the event handler
console.log(getDatalistSelectedOption("input-id","data-foo")) // returns the proper data value
但这似乎不是React中正确的方法。