首页 > 解决方案 > RadioGroup Onchange 没有在 React 中触发

问题描述

我无法找到为什么 onChange 事件在更改检查后没有触发的根本原因,但是,当组件首次加载时 onChange 被调用。

我准备了一个带有一些示例数据的 CodeSandbox。

CodeSandBox 链接

这是组件,

import React from "react";
import styled from "styled-components";
import { checklists } from "./checklists";
import { questions } from "./questions";

const RadioOption = styled.input`
  margin: 10px;
  width: 16px;
  height: 16px;
`;

const RadioGroup = (props) => {
  return React.Children.map(props.children, (child) => {
    if (child.type === RadioOption)
      return React.cloneElement(child, {
        type: "radio",
        defaultChecked: props.value === child.props.value,
        name: props.name,
        disabled: props.disabled,
        onChange: props.handleChange
      });
    return child;
  });
};

class RadioGroupDemo extends React.Component {
  state = {
    checklist: "test_checklist_checklist",
    questions: questions,
    checklists: checklists
  };
  constructor(props) {
    super(props);
    this.onRadioChange = this.onRadioChange(this);
    this.keyCount = 0;
    this.getKey = this.getKey.bind(this);
  }

  onRadioChange = (e) => {
    debugger;
    console.log("handleRadios", e);
    //let q = this.state.questions;
  };

  getKey() {
    return this.keyCount++;
  }

  //first render

  render() {
    console.log(this.state.checklists);
    return (
      <div style={{ maxHeight: "600px", overflow: "auto" }}>
        {this.state.checklist &&
          this.state.checklists.questions[this.state.checklist].map(
            (question) => {
              //debugger;
              let question_id = question.question_id;
              return (
                <div key={`${this.state.checklist}_${question.id}`}>
                  {question.title}

                  <div style={{ width: "120px", flex: "0 0 120px" }}>
                    {(() => {
                      if (
                        typeof this.state.questions[question.id] !== "undefined"
                      ) {
                        return (
                          <RadioGroup
                            name={`field_question_${question.id}`}
                            disabled={this.state.readOnly}
                            value={
                              typeof this.state.questions[question.id].answer ==
                              "undefined"
                                ? this.state.questions[question.id].answer
                                : Object.keys(this.state.questions)
                                    .reduce(
                                      (arr, key) =>
                                        arr.concat(this.state.questions[key]),
                                      []
                                    )
                                    .find((q) => {
                                      return q.question_id === question_id;
                                    }).answer
                            }
                            onChange={this.onRadioChange}
                          >
                            <RadioOption key={this.getKey()} value="yes" />
                            <RadioOption key={this.getKey()} value="no" />
                            <RadioOption key={this.getKey()} value="na" />
                          </RadioGroup>
                        );
                      }
                    })()}
                  </div>
                </div>
              );
            }
          )}
      </div>
    );
  }
}

export default RadioGroupDemo;

请查看代码框并告诉我事件未触发的原因。谢谢

标签: reactjs

解决方案


问题

您将一个onChange道具传递给RadioGroup但访问一个handleChange不存在的道具。

const RadioGroup = (props) => {
  return React.Children.map(props.children, (child) => {
    if (child.type === RadioOption)
      return React.cloneElement(child, {
        type: "radio",
        defaultChecked: props.value === child.props.value,
        name: props.name,
        disabled: props.disabled,
        onChange: props.handleChange, // <-- accessed as handleChange
      });
    return child;
  });
};

在组件中

<RadioGroup
  name={`field_question_${question.id}`}
  disabled={this.state.readOnly}
  value={
    typeof this.state.questions[question.id].answer ==
    "undefined"
      ? this.state.questions[question.id].answer
      : Object.keys(this.state.questions)
          .reduce(
            (arr, key) =>
              arr.concat(this.state.questions[key]),
            []
          )
          .find((q) => {
            return q.question_id === question_id;
          }).answer
  }
  onChange={this.onRadioChange} // <-- passed as onChange
>

RadioGroupDemo你也不要绑定thisonRadioChange处理程序。这个绑定不是必需的,因为onRadioChange它被声明为一个箭头函数,this是自动绑定的。

constructor(props) {
  super(props);
  this.onRadioChange = this.onRadioChange(this); // <-- here
  this.keyCount = 0;
  this.getKey = this.getKey.bind(this);
}

解决方案

this删除在构造函数中绑定到处理程序的尝试。

constructor(props) {
  super(props);
  this.keyCount = 0;
  this.getKey = this.getKey.bind(this);
}

访问正确的道具。

const RadioGroup = (props) => {
  return React.Children.map(props.children, (child) => {
    if (child.type === RadioOption)
      return React.cloneElement(child, {
        type: "radio",
        defaultChecked: props.value === child.props.value,
        name: props.name,
        disabled: props.disabled,
        onChange: props.onChange // <-- onChange
      });
    return child;
  });
};

推荐阅读