如何将基于类的单选按钮组更改为基于功能的单选组

时间:2020-11-11 06:01:06

标签: reactjs radio-group

这是基于类的广播组。我想将其转换为基于功能的广播组。我该怎么做。代码如下:

import React, { Component } from "react";

class Demo2 extends Component {
  constructor() {
    super();
    this.state = {
      name: "React"
    };
    this.onValueChange = this.onValueChange.bind(this);
    this.formSubmit = this.formSubmit.bind(this);
  }

  onValueChange(event) {
    this.setState({
      selectedOption: event.target.value
    });
  }

  formSubmit(event) {
    event.preventDefault();
    console.log(this.state.selectedOption)
  }

  render() {
    return (
      <form onSubmit={this.formSubmit}>
        <div className="radio">
          <label>
            <input
              type="radio"
              value="Male"
              checked={this.state.selectedOption === "Male"}
              onChange={this.onValueChange}
            />
            Male
          </label>
        </div>
        <div className="radio">
          <label>
            <input
              type="radio"
              value="Female"
              checked={this.state.selectedOption === "Female"}
              onChange={this.onValueChange}
            />
            Female
          </label>
        </div>

我希望它为基于功能的组件提供有效的代码。我是新来的,请帮忙。

2 个答案:

答案 0 :(得分:1)

使用const countries = [{...countryStub}, {...countryStub}]; countries[0].communities = [{...communityStub}]; countries[0].countryId = 0; countries[0].communities[0].location = {...locationStub}; countries[0].communities[0].location.country = {...countryStub}; 创建本地状态,然后根据更新后的状态更改模板。

*注意:-功能组件不需要React.useState运算符。 而且您也可以直接返回模板(无需渲染方法)

示例代码:

this

工作代码-https://codesandbox.io/s/bold-platform-yr3l9?file=/src/App.js:0-1001

答案 1 :(得分:1)

import React, { useState } from "react";

function Demo2() {
  const [checked, setChecked] = useState("Male");

  const onValueChange = (event) => {
    setChecked(event.target.value);
  };

  const formSubmit = (event) => {
    event.preventDefault();
    console.log(checked);
  };

  return (
    <form onSubmit={formSubmit}>
      <div className="radio">
        <label>
          <input
            type="radio"
            value="Male"
            checked={checked === "Male"}
            onChange={onValueChange}
          />
          Male
        </label>
      </div>
      <div className="radio">
        <label>
          <input
            type="radio"
            value="Female"
            checked={checked === "Female"}
            onChange={onValueChange}
          />
          Female
        </label>
      </div>
      <div>
        <button type="submit">Submit</button>
      </div>
    </form>
  );
}
相关问题