输入复选框对onChange功能无反应

时间:2020-08-23 11:45:27

标签: javascript reactjs

无法使复选框对其onChange事件做出反应(复选框保持默认状态)。我在这里看到过类似的帖子,但是似乎没有任何作用。我希望换个角度可以帮助弄清楚我的逻辑出了什么问题。

这是 handleChange 函数,并且输入字段的初始值都在父组件中

const [accountData, setAccountData]=useState({accountType:'Free',  //default input value for text input
                                              accountStatus: false }) //default input for checkbox input

const handleSubmit={/*submitLogic*/}       

const handleChange = e =>{
         
const target = e.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
setAccountData({...accountData, [name]:value})
}

//passing the handle change as a prop to the EditView component\\
<EditView  handleChange={handleChange} handleSubmit={handleSubmit} data={accountData}/>

这里是包含输入表单的子组件(关注的是复选框,因为文本输入字段对其onChange事件有反应)

const EditView = ({ handleChange, handleSubmit, data}) =>{
    
const isChecked=data.accountStatus;

<form onSubmit={handleSubmit}>
        <div className="form-row" >
                    <div className="form-group col-md-6">
                     < label htmlFor="accountType">Account Type:</label>
                       <input 
                           type="text"
                           className="form-control" 
                           id="accountType"
                           name="accountType"
                           value={data.accountType}
                            onChange={handleChange}/>
                           
                  </div>
                  <div className="form-group col-md-6">
                      < label htmlFor="accountStatus">Account Status:</label>
                      <div className="custom-control custom-switch">
                        <input 
                            type="checkbox"
                            className="custom-control-input "
                             id="accountStatus"
                             name='accountStatus'
                            checked={isChecked}
                            //value={isChecked}
                            onChange={handleChange}
                            
                            />
                  </div>
             </div>
       <button type='submit' >Submit</button>

</form>
}

我什至尝试创建一个不同的onChange句柄函数,但仍然存在相同的问题。我在上述代码中做错了什么,导致我的复选框未从默认状态更改吗?

2 个答案:

答案 0 :(得分:0)

传递给useState的值是状态的初始值。如果要使用通过属性传递的值,而不在组件本身中进行管理,则不要使用状态。

const EditView = ({handleChange, handleSubmit, data}) => {
  const isChecked = data.accountStatus;

  // ...
};

使用时:

const [isChecked, setIsChecked] = useState(data.accountStatus);

您说的是,我想在此组件中管理isChecked,但是初始值设置为data.accountStatus。因此,以后更改data.accountStatus不会影响isChecked的值,因为只能使用setIsChecked函数进行更改。


在您对问题进行编辑后,复选框不起作用的原因是由于使用了Bootstrap。当您使用自定义表单元素时,Bootstrap将用一些视觉表示(样式元素)替换实际的输入元素。这意味着当您单击Bootstrap复选框/开关时,实际上并没有单击输入。

要解决此问题,我建议使用React Bootstrap,它将Bootstrap集成到React中。这是一个有效的示例(运行代码段后单击“整页”按钮,以防止控制台输出与内容重叠):

const {useState} = React;
const {render} = ReactDOM;
const {Form} = ReactBootstrap;

function App() {
  const [accountData, setAccountData] = useState({
    accountType: "Free",
    accountStatus: false,
  });
  
  const handleChange = ({target}) => {
    const name  = target.name;
    const value = target.type == "checkbox" ? target.checked : target.value;
    setAccountData({...accountData, [name]: value});
  };
  
  console.log(accountData);
  return <EditView data={accountData} onChange={handleChange} />;
}

function EditView({data, onChange}) {
  return (
    <Form>
      <Form.Group>
        <Form.Label>Account Type:</Form.Label>
        <Form.Control
          id="accountType"
          name="accountType"
          type="text"
          value={data.accountType}
          onChange={onChange}
        />
      </Form.Group>
      <Form.Group>
        <Form.Label>Account Status:</Form.Label>
        <Form.Switch
          id="accountStatus"
          name="accountStatus"
          label=""
          checked={data.accountStatus}
          onChange={onChange}
        />
      </Form.Group>
    </Form>
  );
}

render(<App />, document.getElementById("root"));
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" />
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js"></script>
<div id="root"></div>

答案 1 :(得分:0)

尝试一下 Counter.Razor