简体   繁体   English

如何使用react.js处理单选按钮

[英]How to handle radio Buttons with react.js

I'm building a React Component. 我正在构建一个React组件。 This is a form, with a radio button, which can only be set to True and then no longer set back to false. 这是带有单选按钮的表单,只能将其设置为True,然后不能再设置为false。 I would like to be able to turn it on and off. 我希望能够打开和关闭它。 And because worth read out. 而且因为值得一读。
What could the corresponding code look like? 相应的代码是什么样的? At the moment I have that: 目前,我有:

import React, { Component } from 'react';

class Form extends Component {
art = {
selected: "uppper"
}
 onChange() {
console.log("Click")
 }
render() {
 return (
  <form onSubmit={this.handleFormSubmit}>
    <div>
      <label>
        <input type="radio" value="option1"
        onClick={this.onChange} />
        option1
      </label>
    </div>  
    <input type="submit" value="Submit" />
   </form>
   );
  }
 } 
export default Form;

while being consistent with using a class-component, your code would look something like this: 在与使用类组件保持一致的同时,您的代码将如下所示:

class Form extends Component {
  state = {
    selected: false
  };
  onChange = () => {
    this.setState({
      selected: !this.state.selected
    });
  };
  render() {
    return (
      <form onSubmit={this.handleFormSubmit}>
        <div>
          <label>
            <input
              type="radio"
              value="option1"
              onClick={this.onChange}
              checked={this.state.selected}
            />
            option1
          </label>
        </div>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
export default Form;

Essentially what you need are 3 things. 本质上,您需要做的是三件事。

  1. A Boolean value in your state to keep track of the button was clicked (true or false). 单击了处于您状态的布尔值以跟踪按钮(对或错)。
  2. Give the input a checked property which matches the value of the selected state. 为输入提供一个选中属性,该属性与所选状态的值匹配。
  3. Update the onChange handler to toggle the state value. 更新onChange处理程序以切换状态值。 Also ensure that the onChange handler is bound to the execution context by using an arrow function or binding the this keyword. 还通过使用箭头函数或绑定this关键字,确保onChange处理程序绑定到执行上下文。

See working sandbox: https://codesandbox.io/s/mystifying-borg-gwl2q 查看有效的沙箱: https : //codesandbox.io/s/mystifying-borg-gwl2q

Here's how you can do this: 这是您可以执行的操作:

import React, { useState } from 'react';
import { render } from 'react-dom';

const App = () => { 
  const [radioState, setRadioState] = useState(false);

  const handleChange = () => { 
    setRadioState(!radioState)
  }

  return (
    <input type="radio" checked={radioState} onClick={handleChange}/>
  )
}

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

Live example here . 这里的例子。

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

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