求JSP中<s:radio>标签对应的React等价实现方案
Struts单选框标签的React等价实现
对应Java数据结构
public class RadioOptions{ private String key; private String value; // getter and setter methods }
数据初始化示例
List<RadioOptions> radioOption = new ArrayList<RadioOptions>(); radioOption.add(new RadioOptions("1", "This is option 1.")); radioOption.add(new RadioOptions("2", "This is option 2.")); radioOption.add(new RadioOptions("3", "This is option 3.")); radioOption.add(new RadioOptions("4", "This is option 4."));
待转换的Struts单选框标签
<s:radio label="Please select the best choice" name="answer" list="radioOption" listKey="key" listValue="value" value="1" />
React等价实现
以下是对应功能的React函数组件实现,包含相同的单选选择、默认选中、值绑定逻辑:
import { useState } from 'react'; function RadioGroup() { // 模拟后端返回的选项数据,对应Java端的radioOption列表 const radioOptions = [ { key: "1", value: "This is option 1." }, { key: "2", value: "This is option 2." }, { key: "3", value: "This is option 3." }, { key: "4", value: "This is option 4." } ]; // 初始化选中值,对应原Struts标签的默认选中配置 const [selectedAnswer, setSelectedAnswer] = useState("1"); const handleChange = (e) => { setSelectedAnswer(e.target.value); }; return ( <div> <label>Please select the best choice</label> <div> {radioOptions.map(option => ( <div key={option.key}> <input type="radio" name="answer" value={option.key} checked={selectedAnswer === option.key} onChange={handleChange} /> <label>{option.value}</label> </div> ))} </div> </div> ); } export default RadioGroup;
实现说明
- 用
useState管理选中状态,默认值设为"1",和原Struts标签的默认选中逻辑一致 - 遍历选项列表生成单选框,统一设置
name为"answer"保证单选互斥 - 单选框的
value对应Java对象的key,显示文本对应value字段 - 绑定
onChange事件同步选中状态,确保UI与数据状态一致
内容的提问来源于stack exchange,提问作者Prash
相关产品推荐
相关产品推荐

