You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React实现页面加载时按属性启用/禁用CheckboxList

解决React CheckboxList根据XML属性设置禁用状态的问题

要实现你需要的功能,只需在渲染复选框时根据is-assigned属性添加禁用控制,并可优化选中逻辑确保严谨性,具体修改如下:

核心修改点

  • 给复选框添加disabled属性:根据item.attributes["is-assigned"]的值判断,值为"FALSE"时禁用,"TRUE"时启用
  • (可选)在handleChange中增加校验,确保只有启用状态的项能被修改选中状态

修改后的完整代码

XML数据示例

<?xml version="1.0"?>
<Product>
  <states is-assigned="FALSE" product-state-id="11">Alabama</states>
  <states is-assigned="FALSE" product-state-id="12">Alaska</states>
  <states is-assigned="FALSE" product-state-id="21">Arizona</states>
  <states is-assigned="TRUE" product-state-id="22">Colorado</states>
  <states is-assigned="TRUE" product-state-id="33">Connect</states>
</Product>

修改后的React组件

export class AssignStates extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      Template_ID: "",
      templatestates: [],
      checkedItems: [],
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    const id = Number(event.target.id);
    // 额外校验:禁用状态的复选框不处理选中逻辑
    if (event.target.disabled) return;

    const index = this.state.checkedItems.indexOf(id);
    const updatedArray = [...this.state.checkedItems];
    if (index !== -1) {
      updatedArray.splice(index, 1);
    } else {
      updatedArray.push(id);
    }
    this.setState({
      checkedItems: updatedArray
    });
  }

  componentDidUpdate(prevProps) {
    const Template_ID = this.props.key_id;
    if (prevProps.key_id !== this.props.key_id) {
      console.log(`key_id: ${this.props.key_id}`);
      this.getListOfStates(Template_ID);
    }
  }

  getListOfStates(Template_ID) {
    axios
      .get(REQUEST_URL, { "Content-Type": "application/xml; charset=utf-8" })
      .then((response) => {
        const jsonDataFromXml = new XMLParser().parseFromString(response.data);
        const states = jsonDataFromXml.getElementsByTagName("states");
        console.log(states);
        this.setState({
          templatestates: states,
          checkedItems: states
            .filter(({ attributes }) => attributes["is-assigned"] === "TRUE")
            .map(({ attributes }) => Number(attributes["product-state-id"]))
        });
      });
  }

  render() {
    return (
      <div>
        <form>
          <div>
            <ul>
              {this.state.templatestates.map((item) => {
                const isAssigned = item.attributes["is-assigned"] === "TRUE";
                const stateId = Number(item.attributes["product-state-id"]);
                return (
                  <li key={stateId}>
                    <label>
                      <input
                        type="checkbox"
                        id={stateId}
                        checked={this.state.checkedItems.includes(stateId)}
                        value={item.value}
                        onChange={this.handleChange}
                        // 根据is-assigned属性设置禁用状态
                        disabled={!isAssigned}
                      />
                      &nbsp; {item.value}
                    </label>
                  </li>
                );
              })}
            </ul>
          </div>
          <button type="submit">Submit</button>
        </form>
      </div>
    );
  }
}

export default AssignStates;

说明

  • 渲染时通过disabled={!isAssigned}直接控制复选框禁用状态,isAssigned由XML的is-assigned属性转换而来
  • handleChange中增加的禁用校验,避免意外触发时修改禁用项的选中状态,提升代码健壮性
  • 提前提取isAssigned和stateId变量,让代码更清晰易读

内容的提问来源于stack exchange,提问作者TestUser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 12:15:30