我是ReactJS的新手,如果这听起来很不好意思。我有一个组件,根据接收到的数据创建几个表行。

列中的每个单元格都有一个单选复选框。因此,用户可以从现有行中选择一个site_name和一个地址。所选内容应显示在页脚中。这就是我被困住的地方。

var SearchResult = React.createClass({
  render: function () {
    var resultRows = this.props.data.map(function (result) {
      return (
        <tbody>
          <tr>
            <td>
              <input type="radio" name="site_name" value={result.SITE_NAME}>
                {result.SITE_NAME}
              </input>
            </td>
            <td>
              <input type="radio" name="address" value={result.ADDRESS}>
                {result.ADDRESS}
              </input>
            </td>
          </tr>
        </tbody>
      );
    });
    return (
      <table className="table">
        <thead>
          <tr>
            <th>Name</th>
            <th>Address</th>
          </tr>
        </thead>
        {resultRows}
        <tfoot>
          <tr>
            <td>chosen site name ???? </td>
            <td>chosen address ????? </td>
          </tr>
        </tfoot>
      </table>
    );
  },
});

在jQuery中,我可以做一些像$("input[name=site_name]:checked").val()这样的事情来获得一个radio复选框类型的选择,并将其插入到第一个页脚单元格中。

但肯定有一个Reactjs的方式,我完全错过了?非常感谢


当前回答

下面是在react js中实现单选按钮的最简单方法。

class App extends React.Component { setGender(event) { console.log(event.target.value); } render() { return ( <div onChange={this.setGender.bind(this)}> <input type="radio" value="MALE" name="gender"/> Male <input type="radio" value="FEMALE" name="gender"/> Female </div> ) } } ReactDOM.render(<App/>, document.getElementById('app')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div>

编辑

你可以使用箭头函数代替绑定。将上面的代码替换为

<div onChange={event => this.setGender(event)}>

对于默认值,使用defaultChecked,如下所示

<input type="radio" value="MALE" defaultChecked name="gender"/> Male

其他回答

import React from 'react';
import './style.css';

export default function App() {
  const [currentRadioValue, setCurrentValue] = React.useState('on');
  const handleRadioChange = value => {
    setCurrentValue(value);
  };
  return (
    <div>
      <>
        <div>
          <input
            name="radio-item-1"
            value="on"
            type="radio"
            onChange={e => setCurrentValue(e.target.value)}
            defaultChecked={currentRadioValue === 'on'}
          />
          <label htmlFor="radio-item-1">Radio Item 1</label>
          {currentRadioValue === 'on' && <div>one</div>}
        </div>
        <div>
          <input
            name="radio-item-1"
            value="off"
            type="radio"
            onChange={e => setCurrentValue(e.target.value)}
            defaultChecked={currentRadioValue === 'off'}
          />
          <label htmlFor="radio-item-2">Radio Item 2</label>
          {currentRadioValue === 'off' && <div>two</div>}
        </div>
      </>
    </div>
  );
}

工作示例:https://stackblitz.com/edit/react-ovnv2b

我也搞混了无线电,复选框的实现。我们需要的是,监听收音机的变化事件,然后设置状态。我举了一个性别选择的小例子。

/* * A simple React component */ class App extends React.Component { constructor(params) { super(params) // initial gender state set from props this.state = { gender: this.props.gender } this.setGender = this.setGender.bind(this) } setGender(e) { this.setState({ gender: e.target.value }) } render() { const {gender} = this.state return <div> Gender: <div> <input type="radio" checked={gender == "male"} onClick={this.setGender} value="male" /> Male <input type="radio" checked={gender == "female"} onClick={this.setGender} value="female" /> Female </div> { "Select Gender: " } {gender} </div>; } } /* * Render the above component into the div#app */ ReactDOM.render(<App gender="male" />, document.getElementById('app')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div>

根据陈康的回答,我有一个更干练的方法给感兴趣的人:

class RadioExample extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedRadio: 'public'
    };
  }

  handleRadioChange = (event) => {
    this.setState({
      selectedRadio: event.currentTarget.value
    })
  };

  render() {
    return (
      <div className="radio-row">
        <div className="input-row">
          <input
            type="radio"
            name="public"
            value="public"
            checked={this.state.selectedRadio === 'public'}
            onChange={this.handleRadioChange}
          />
          <label htmlFor="public">Public</label>
        </div>
        <div className="input-row">
          <input
            type="radio"
            name="private"
            value="private"
            checked={this.state.selectedRadio === 'private'}
            onChange={this.handleRadioChange}
          />
          <label htmlFor="private">Private</label>
        </div>
      </div>
    )
  }
}

除了这个会有一个默认的选中值。

@Tomasz Mularczyk在他的回答中提到了react钩子,但我认为我应该加入一个我最近使用的解决方案,只使用useState钩子。

function Radio() {
  const [currentRadioValue, setCurrentRadioValue] = useState()

  const handleRadioChange = (e) => {
    setCurrentValue(e.target.value);
  };

  return ( 
    <>
      <div>
        <input
          id="radio-item-1"
          name="radio-item-1"
          type="radio"
          value="radio-1"
          onChange={handleRadioChange}
          checked={currentRadioValue === 'radio-1'}
        />
        <label htmlFor="radio-item-1">Radio Item 1</label>
      </div>
      <div>
        <input
          id="radio-item-2"
          name="radio-item-2"
          type="radio"
          value="radio-2"
          onChange={handleRadioChange}
          checked={currentRadioValue === 'radio-2'}
        />
        <label htmlFor="radio-item-2">
          Radio Item 1
        </label>
      </div>
    </>
  );
}
import React, { Component } from "react";

class RadionButtons extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // gender : "" , // use this one if you don't wanna any default value for gender
      gender: "male" // we are using this state to store the value of the radio button and also use to display the active radio button
    };

    this.handleRadioChange = this.handleRadioChange.bind(this);  // we require access to the state of component so we have to bind our function 
  }

  // this function is called whenever you change the radion button 
  handleRadioChange(event) {
      // set the new value of checked radion button to state using setState function which is async funtion
    this.setState({
      gender: event.target.value
    });
  }


  render() {
    return (
      <div>
        <div check>
          <input
            type="radio"
            value="male" // this is te value which will be picked up after radio button change
            checked={this.state.gender === "male"} // when this is true it show the male radio button in checked 
            onChange={this.handleRadioChange} // whenever it changes from checked to uncheck or via-versa it goes to the handleRadioChange function
          />
          <span
           style={{ marginLeft: "5px" }} // inline style in reactjs 
          >Male</span>
        </div>
        <div check>
          <input
            type="radio"
            value="female"
            checked={this.state.gender === "female"}
            onChange={this.handleRadioChange}
          />
          <span style={{ marginLeft: "5px" }}>Female</span>
        </div>
      </div>
    );
  }
}
export default RadionButtons;