【问题标题】:Is it possible to unselect <Radio /> by clicking selected one (in React)?是否可以通过单击选定的一个(在 React 中)取消选择 <Radio />?
【发布时间】:2019-05-16 11:17:42
【问题描述】:

是否可以通过单击选定的收音机来取消选择收音机?

我知道这是默认浏览器行为,但我一直在研究这个自定义功能。

Material-ui 也不能这样做。

我知道Material-ui&lt;input type="radio"&gt; 包裹在&lt;label /&gt; 中,看起来像这样:

<label>
  <input type="radio" onChange={() => {}}>
</label>

如果我想实现这个功能,我将不得不将onChange 替换为onClick,但随后浏览器会对我大喊&lt;input /&gt; 应该有onChange 事件处理程序。

那么我如何正确地将onChangeonClick 事件处理程序挂钩?

我应该只给onChange 事件一个空函数吗?还是我应该打电话给preventDefault

【问题讨论】:

    标签: javascript html reactjs forms input


    【解决方案1】:

    查看this网址

    import React, { Component } from 'react';
    import { render } from 'react-dom';
    import Hello from './Hello';
    import './style.css';
    
    class App extends Component {
      constructor() {
        super();
        this.state = {
          group1:[{"value":"1"},
          {"value":"2"},
          {"value":"3"}],
          group1Selected:null,
          group2:[{"value":"1"},
          {"value":"2"},
          {"value":"3"}],
           group2Selected:null,
        };
      }
      ChangeOption = (i,group) =>{
        var groupData = this.state[group] == i?null:i;        
        this.setState({[group]:groupData})
      }
      render() {
        const {group1,group2,group1Selected,group2Selected} = this.state;
        return (
          <div>
            {
              group1.map( (data,i)=><><input type="radio" id={`1-${i}`} onClick={e=>this.ChangeOption(i,"group1Selected")} checked={i==group1Selected?true:false} name="1" value={data.value}/><label for={`1-${i}`}>{data.value}</label></>)
            }
            <br/>
            {
              group2.map( (data,i)=><><input id={`2-${i}`} onClick={e=>this.ChangeOption(i,"group2Selected")} type="radio" checked={i==group2Selected?true:false} name="2" value={data.value}/><label for={`2-${i}`}>{data.value}</label></>)
            }
          </div>
        );
      }
    }
    
    render(<App />, document.getElementById('root'));
    
    
    

    【讨论】:

    猜你喜欢
    • 2011-02-15
    • 2014-10-16
    • 2018-06-24
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 2016-10-02
    • 2021-06-20
    • 1970-01-01
    相关资源
    最近更新 更多