怎样给radio分组呢?

在前端开发中,对 radio buttons 进行分组主要依靠 name 属性。所有拥有相同 name 属性值的 radio buttons 会被视为同一组。这意味着,在一个组中,用户一次只能选择一个 radio button。

以下是一些示例,展示如何在不同的前端框架/库中实现 radio button 分组:

1. 纯 HTML:

<label for="option1">Option 1</label>
<input type="radio" id="option1" name="group1" value="1">

<label for="option2">Option 2</label>
<input type="radio" id="option2" name="group1" value="2">

<br>

<label for="option3">Option 3</label>
<input type="radio" id="option3" name="group2" value="3">

<label for="option4">Option 4</label>
<input type="radio" id="option4" name="group2" value="4">

在这个例子中,"Option 1" 和 "Option 2" 属于 group1,而 "Option 3" 和 "Option 4" 属于 group2

2. React:

import React, { useState } from 'react';

function MyComponent() {
  const [selectedValue, setSelectedValue] = useState('');

  const handleChange = (event) => {
    setSelectedValue(event.target.value);
  };

  return (
    <div>
      <label>
        Option 1
        <input type="radio" name="group1" value="1" checked={selectedValue === '1'} onChange={handleChange} />
      </label>
      <label>
        Option 2
        <input type="radio" name="group1" value="2" checked={selectedValue === '2'} onChange={handleChange} />
      </label>

      <br />

      <label>
        Option 3
        <input type="radio" name="group2" value="3" checked={selectedValue === '3'} onChange={handleChange} />
      </label>
      <label>
        Option 4
        <input type="radio" name="group2" value="4" checked={selectedValue === '4'} onChange={handleChange} />
      </label>
    </div>
  );
}

export default MyComponent;

在 React 中,我们使用 name 属性进行分组,并通过 checked 属性和 onChange 事件处理程序来管理选中状态。

3. Vue.js:

<template>
  <div>
    <label>
      Option 1
      <input type="radio" name="group1" value="1" v-model="selectedValue">
    </label>
    <label>
      Option 2
      <input type="radio" name="group1" value="2" v-model="selectedValue">
    </label>

    <br>

    <label>
      Option 3
      <input type="radio" name="group2" value="3" v-model="selectedValue">
    </label>
    <label>
      Option 4
      <input type="radio" name="group2" value="4" v-model="selectedValue">
    </label>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedValue: '',
    };
  },
};
</script>

在 Vue.js 中,v-model 指令简化了状态管理,但 name 属性仍然是分组的关键.

4. Angular:

import { Component } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: `
    <div>
      <label>
        Option 1
        <input type="radio" name="group1" value="1" [(ngModel)]="selectedValue">
      </label>
      <label>
        Option 2
        <input type="radio" name="group1" value="2" [(ngModel)]="selectedValue">
      </label>

      <br>

      <label>
        Option 3
        <input type="radio" name="group2" value="3" [(ngModel)]="selectedValue">
      </label>
      <label>
        Option 4
        <input type="radio" name="group2" value="
posted @ 2024-11-27 08:53  王铁柱6  阅读(74)  评论(0)    收藏  举报