【问题标题】:How to handle when a radio button is clicked?单击单选按钮时如何处理?
【发布时间】:2020-07-23 12:04:47
【问题描述】:

我希望在单击单选按钮时调用一个函数。在这个函数中会有一个二维数组,格式如下:

[[0,0],[1,0],[2,1],[3,0],[4,1]]

数组条目如下所示:[regionNumber, 0 or 1 ]

  • regionNumber 对应于以0 开头的区域号
  • 0 是相应的单选按钮尚未被点击。
  • 1 是相应的单选按钮已被单击。

我会将这个二维数组传递给另一个组件使用。

当一个单选按钮被点击时,它会在二维数组中被识别,对应的0/1会被切换为相反的值。

例如:

// this means `regionNumber` 2 and `regionNumber` 4 radio buttons are checked.
[ [0,0], [1,0], [2,1], [3,0], [4,1] ]

// if we click the radio button 4 again (`regionNumber` 4) then it will turn into:    
[ [0,0] , [1,0] , [2,1] , [3,0] , [4,0] ]

选中单选按钮后,将该数组对象发送到 Graph。 例如,当检查[object1,object2,object3] = object1object2 时,它们将完成此操作。

import React from 'react';
import { MDBFormInline } from 'mdbreact';
import { MDBBtn } from "mdbreact";
import { Container } from 'reactstrap';
import $ from "jquery";

const Test = props => {
  const total_regions = (JSON.parse(JSON.stringify(props.test)).length); // gets the number of regions

  return (
    // displays radio buttons depending on the number of objects in json

    <div>
    {props.test.map((item, idx) => { 
      return (
        <label key={idx}>
          <input className="region" type="radio" value={idx} />
          <span>{idx}</span> 
        </label>
      );
    })}
    </div>

  );
};
export default Test;

我正在考虑做一个 jQuery,但因为我要在函数中处理一个数组,所以我不确定 jQuery 是否可以这样做,因为我还将在函数中调用另一个组件。

我尝试在单选按钮中添加onClick,但我认为我没有正确使用它。

有人有任何指导吗?

【问题讨论】:

  • 这可能会成为一个问题,因为您必须查找很多次。你为什么不尝试对象类型的方法? { "0": 1, "1":0 } ?更新数据和解析应该更容易
  • 对于事件,你应该使用 onchange 事件而不是 onclick

标签: javascript arrays reactjs button mdbreact


【解决方案1】:

只需使用onClick。这是一个你应该能够适应的例子。

const Test = props => {
  const total_regions = JSON.parse(JSON.stringify(props.test)).length; // gets the number of regions
  const handleClick = (item, idx) => {
    console.log(`item ${item} with index ${idx} clicked`);
  };

  return (
    // displays radio buttons depending on the number of objects in json

    <div>
      {props.test.map((item, idx) => {
        return (
          <label key={idx}>
            <input
              className="region"
              type="radio"
              value={idx}
              onClick={() => handleClick(item, idx)}
            />
            <span>{idx}</span>
          </label>
        );
      })}
    </div>
  );
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-26
    • 2013-03-05
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多