我是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的方式,我完全错过了?非常感谢


当前回答

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

其他回答

单击单选按钮应该触发一个事件,其中之一:

如果只希望选择知识是本地的,则调用setState 调用一个从上面传入的回调函数self.props.selectionChanged(…)

在第一种情况下,改变状态将触发重新渲染,你可以这样做 <td>所选站点名称{this.state. name。chosenSiteName} < / td >

在第二种情况下,回调的源将更新内容,以确保您的SearchResult实例将有chosenSiteName和chosenAddress设置在它的props中。

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;

任何对渲染的改变都应该通过状态或道具(react doc)来改变。

所以这里我注册了输入的事件,然后改变状态,这将触发渲染显示在页脚上。

var SearchResult = React.createClass({
  getInitialState: function () {
    return {
      site: '',
      address: '',
    };
  },
  onSiteChanged: function (e) {
    this.setState({
      site: e.currentTarget.value,
    });
  },

  onAddressChanged: function (e) {
    this.setState({
      address: e.currentTarget.value,
    });
  },

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

jsbin

我们是这样做的:


export default function RadioButton({ onChange, option }) {
    const handleChange = event => {
        onChange(event.target.value)
    }

    return (
        <>
            <div className="custom-control custom-radio">
                <input
                    type="radio"
                    id={ option.option }
                    name="customRadio"
                    className="custom-control-input"
                    onChange={ handleChange }
                    value = { option.id }
                    />
                    <label
                        className="custom-control-label"
                        htmlFor={ option.option }
                        >
                        { option.option }
                    </label>
            </div>
        </>
    )
}

这是我用过的。希望这能有所帮助。 首先定义变量。

const [variableName, setVariableName] = useState("");

然后,我们将需要实际的单选按钮。

<input
   type="radio"
   name="variableName"
   value="variableToCheck"
   onChange={(e) =>
   setVariableName("variableToCheck")
   }
   checked={variableName === "variableToCheck"}
/>