reactjs 选中第二个项目时,单选按钮选中不适用于更改

b09cbbtk  于 2023-03-08  发布在  React
关注(0)|答案(2)|浏览(103)

我试图在React中创建一个Raidobutton。下面是代码。当我点击第一个单选按钮(“Windows”),单选按钮显示选中,当我点击第二个单选按钮(“Mac”),单选按钮不显示选中,即使选中是真的。当我们再次点击“Mac”单选按钮被选中。之后,所有的单选按钮工作正常。有人能帮助这个吗?

import './App.css';
import { useState } from 'react';

const options = ["Windows", "Mac", "Linux"]
const days = ["Male", "Female"]

const TempRadio = ({ item, group }) => {

  const [checked, setChecked] = useState('')
  const handleChnage = (e) => {
    console.log(e.target.value)
    setChecked(() => e.target.value)
  }
  return (
    <label>
      <input type="radio" value={item} checked={item === checked} name={group} onChange={ handleChnage} />{item}
    </label>

  )
}
function App() {

  const renderItems = (items, group) => {
    return <div className='myul'>{items.map((item) =>
      <TempRadio item={item} key={item} group={group} />

    )}</div>

  }
  return (
    <div className="App">
      <header className="App-header">
        <h1>
          Which OS?
        </h1>
        {renderItems(options, "OS")}
        <h2>Gender</h2>
        {renderItems(days, "time")}
      </header>
    </div>
  );
}

export default App;
iaqfqrcu

iaqfqrcu1#

您创建单选按钮的方法不对。因为您给每个单选按钮指定了自己的状态,所以它将无法工作:
你需要的是这样的东西:

import './App.css';
import { useState } from 'react';

function App() {
  const [checked, setChecked] = useState('');

  const options = ['Windows', 'Mac', 'Linux'];
  const days = ['Male', 'Female'];

  const handleChnage = (e) => {
    console.log(e.target.value);
    setChecked(() => e.target.value);
  };

  console.log(checked);

  const renderItems = (items, group) => {
    return (
      <div className="myul">
        {items.map((item) => (
          <label>
            <input
              type="radio"
              value={item}
              checked={item === checked}
              name={group}
              onChange={handleChnage}
            />
            {item}
          </label>
        ))}
      </div>
    );
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1>Which OS?</h1>
        {renderItems(options, 'OS')}
        <h2>Gender</h2>
        {renderItems(days, 'time')}
      </header>
    </div>
  );
}

export default App;
5rgfhyps

5rgfhyps2#

由于您正在对单选按钮进行分组,并且您可能希望对两个集合的输出执行"某些操作",因此转移状态管理的职责to the parent component(在本例中为App)是有意义的。
因此,在app中,state是一个对象,它使用group值作为键,并使用所单击单选按钮的值作为其值。
在这个例子中,我创建了一个RadioGroup组件来帮助管理数据流,在这里传递了相应的选项,以及组标签、组名称、该组的状态和共享处理程序。
(The useEffect是临时的--它只是显示当每个单选按钮组中的按钮发生变化时状态是如何更新的。我还重新标记了days/time变量,因为它似乎与实际内容--性别--没有关系。)

const { useEffect, useState, Fragment } = React;

function App({ os, gender }) {

  // Initialise the state as an object with
  // OS and gender properties
  const [ radios, setRadios ] = useState({ os: '', gender: '' });
  
  // The value of the clicked radio, and its group, are
  // passed to the handler (which is itself passed to the
  // component). The value of the group in the state object
  // is updated
  function handleUpdate(value, group) {
    setRadios(prev => {
      return { ...prev, [group]: value };
    });
  }

  // An effect to show how state changes
  useEffect(() => console.log(radios), [radios]);

  // Add the RadioGroup components, passing down the state for
  // the group, and the handler
  return (
    <main className="App">
      <RadioGroup
        options={os}
        group="os"
        label="OS"
        checked={radios.os}
        handleUpdate={handleUpdate}
      />
      <RadioGroup
        options={gender}
        group="gender"
        label="Gender"
        checked={radios.gender}
        handleUpdate={handleUpdate}
      />
    </main>
  );
}

function RadioGroup(props) {

  const {
    options,
    group,
    label,
    handleUpdate,
    checked
  } = props;

  // When a radio button is clicked we extract the value, and
  // name from it (relabelling `name` as `group` for
  // consistency, and then call the handler with those values
  function handleChange(e) {
    if (e.target.matches('input[type="radio"]')) {
      const { value, name: group } = e.target;
      handleUpdate(value, group);
    }
  }

  // For convenience we add the change listener to the
  // the radio button section so it can catch events from
  // its children as they bubble up the DOM
  return (
    <section class="radiogroup" onChange={handleChange}>
      <h1>{label}</h1>
      {options.map(option => {
        return (
          <Fragment>
            <label>{option}</label>
            <input
              type="radio"
              checked={option === checked}
              value={option}
              name={group}
            />
          </Fragment>
        );
      })}
    </section>
  );

}

const os = ['Windows', 'Mac', 'Linux'];
const gender = ['Male', 'Female'];

ReactDOM.render(
  <App os={os} gender={gender} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

相关问题