简体   繁体   English

如何在 ReactJs 中使用 RadioButton 设置状态

[英]How to setState using RadioButton in ReactJs

I was trying to setState using the radiobuttons in ReactJs but I dont know why this is not working, maybe I have something missing in my code我试图在 ReactJs 中使用单选按钮设置状态,但我不知道为什么这不起作用,也许我的代码中缺少一些东西

  var handleRadio = (event)=>{
      this.setState({views:event.target.value})
     
    }
    

This is my Function "handleRadio"这是我的函数“handleRadio”

 <input
                    type="radio"
                    checked={this.state.views === "streets-v11"}
                    onClick={handleRadio} 
                    value="streets-v11"
                /> Street Map <br />
                <input
                    type="radio"
                    checked={this.state.views === 'outdoors-v11'}
                    onClick={handleRadio} 
                    value="outdoors-v11"
                /> Topo Map <br />
                    <input
                    type="radio"
                    checked={this.state.views === 'satellite-v9'}
                    onClick={handleRadio} 
                    value="satellite-v9"
                /> Satellite Map  

and that's my code for buttons.. I was trying to call the function on radio button click and then according to that I was trying to set the value of state but this code is not working to setState in my project What's Wrong in this code ?这是我的按钮代码.. 我试图在单选按钮单击时调用该函数,然后根据该函数我试图设置 state 的值,但是这段代码在我的项目中无法用于 setState 这段代码有什么问题? my state name is views initialized as an empty string....我的状态名称是初始化为空字符串的视图....

I think you should use OnChange instead the OnClick prop我认为你应该使用 OnChange 而不是 OnClick 道具

change onClick={handleRadio} to OnChange={handleRadio}onClick={handleRadio}更改为OnChange={handleRadio}

Here is a complete example这是一个完整的例子

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      views: [
        { txt: 'streets-v11', value: false },
        { txt: 'outdoors-v11', value: true },
        { txt: 'satellite-v9', value: true }
      ]
    };
    this.handleRadio = this.handleRadio.bind(this);
  }

  handleRadio(e) {
    let views = this.state.views.slice(0);
    views = views.map((v) => {
      if (v.txt === e.target.name) v.value = !v.value;
      return v;
    });
    this.setState({ ...this.state, views });
  }

  render() {
    return (
      <h1>
        {this.state.views.map((v) => {
          return (
            <div key={v.txt}>
              <input
                name={v.txt}
                type="radio"
                checked={v.value}
                onClick={this.handleRadio}
              />
              {v.txt}
            </div>
          );
        })}
      </h1>
    );
  }
}

render(<App />, document.querySelector('#root'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM