

新闻资讯
技术学院在React应用中,从
在React开发中,我们经常需要构建交互式表单,其中
HTML
最推荐和符合React范式的方法是,在
假设我们有以下运费费率数据:
const rates = [
{ id: 'r8f8hd8', service: 'Standard Shipping', amount: 45 },
{ id: 'r8f8hd', service: 'Express Shipping', amount: 450 },
{ id: 'r8f8hd9', service: 'Economy Shipping', amount: 20 },
];我们可以将每个费率的id作为
示例代码:
import React, { useState } from 'react';
function ShippingRateSelector() {
const rates = [
{ id: 'r8f8hd8', service: 'Standard Shipping', amount: 45 },
{ id: 'r8f8hd', service: 'Express Shipping', amount: 450 },
{ id: 'r8f8hd9', service: 'Economy Shipping', amount: 20 },
];
const [selectedRate, setSelectedRate] = useState(null);
const handleRateChange = (e) => {
const selectedRateId = e.target.value;
// 从原始数据数组中查找完整的费率对象
const rateDetails = rates.find(rate => rate.id === selectedRateId);
setSelectedRate(rateDetails);
console.log('Selected Rate ID:', selectedRateId);
console.log('Selected Rate Details:', rateDetails);
};
return (
{selectedRate && (
当前选择的费率:
服务: {selectedRate.service}
金额: ${selectedRate.amount}
ID: {selectedRate.id}
)}
);
}
export default ShippingRateSelector;注意事项:
虽然不推荐,但如果你确实需要从DOM层面直接获取多个值,可以利用e.target.options集合。这种方法涉及到将数组索引或其他标识符存储在value中,然后通过该索引访问DOM中的option元素,进而获取其自定义属性。
示例代码:
import React, { useState } from 'react';
function ShippingRateSelectorAlternative() {
const rates = [
{ id: 'r8f8hd8', service: 'Standard Shipping', amount: 45 },
{ id: 'r8f8hd', service: 'Express Shipping', amount: 450 },
{ id: 'r8f8hd9', service: 'Economy Shipping', amount: 20 },
];
const [selectedRateDetails, setSelectedRateDetails] = useState(null);
const handleRateChange = (e) => {
// e.target.value 此时是选项的索引(字符串形式)
const selectedIndex = parseInt(e.target.value, 10);
// 获取对应的DOM option元素
// 注意:e.target.options 是一个HTMLCollection,通过索引访问
// 还需要考虑第一个 disabled option 占用的索引
const selectedOption = e.target.options[selectedIndex];
if (selectedOption) {
// 从原始 rates 数组中根据索引获取数据 (selectedIndex - 1 是因为第一个是 disabled option)
const rateDetails = rates[selectedIndex - 1]; // 假设 rates 数组顺序与 option 对应
setSelectedRateDetails(rateDetails);
console.log('Selected Option DOM:', selectedOption);
console.log('Selected Rate Details (from array):', rateDetails);
// 如果需要,也可以尝试从DOM元素读取自定义属性,但这通常不推荐
// const customId = selectedOption.getAttribute('data-id');
// const customAmount = selectedOption.getAttribute('data-amount');
}
};
return (
{selectedRateDetails && (
当前选择的费率 (替代方案):
服务: {selectedRateDetails.service}
金额: ${selectedRateDetails.amount}
ID: {selectedRateDetails.id}
)}
);
}
export default ShippingRateSelectorAlternative;注意事项:
在React中从