【问题标题】:React Cannot read property 'getAttribute' of undefinedReact无法读取未定义的属性'getAttribute'
【发布时间】:2019-01-11 15:29:33
【问题描述】:

尝试编译我的应用程序TypeError: Cannot read property 'getAttribute' of undefined 时出现以下错误。

我无法找到这行中的原因:if (event.target.getAttribute('name') && !sectionsClicked.includes(event.target.getAttribute('name'))) { 是错误

这是主要的反应组件

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      progressValue: 0,
      sectionsClicked: [],
    };

    this.handleProgress = this.handleProgress.bind(this);
  }


  handleProgress = (event) => {
    const { progressValue } = this.state;
    console.log(progressValue);
    const { sectionsClicked } = this.state;
    if (event.target.getAttribute('name') && !sectionsClicked.includes(event.target.getAttribute('name'))) {
      this.setState({
        progressValue: Math.floor((sectionsClicked.length / 77) * 100),
        sectionsClicked: sectionsClicked.push(event.target.getAttribute('name')),
      });
      console.log(sectionsClicked);
    }
  };

  render() {
    const { questions } = this.props;
    const { progressValue } = this.state;
    const groupByList = groupBy(questions.questions, 'type');
    const objectToArray = Object.entries(groupByList);


    return (
      <>
        <Progress value={progressValue} />
        <div className="text-center mt-5">
          <ul>
            {questionListItem && questionListItem.length > 0 ?
              (
                <Wizard
                  onChange={(event) => this.handleProgress(event)}
                  initialValues={{ employed: true }}
                  onSubmit={() => {
                    window.alert('Hello');
                  }}
                >
                  {questionListItem}
                </Wizard>
              ) : null
            }
          </ul>
        </div>
      </>
    );
  }
}

【问题讨论】:

标签: reactjs


【解决方案1】:

根据文档:

https://github.com/final-form/react-final-form#onchange-formstate-formstate--void

传递给onChange 的预期参数是formState 而不是事件。尝试记录传递给函数的参数,它可能具有您需要的更改。

【讨论】:

    【解决方案2】:

    最初在&lt;Wizard&gt; 中调用onChange(向上报告给&lt;App&gt;)的&lt;FormSpy&gt; 组件传递了一个不是事件的参数。它的类型为FormState

    在该类型上,target 属性是 undefined,因此您看到的错误。

    如果您在文档中看到该对象的属性,您可能会通过检查表单的脏字段并找到相关的 DOM 元素来获得所需的内容。

    不过,您很可能可以找到一种方法来实现所需的行为,而根本无需借助 DOM 属性。相同的 dirtyFields 属性具有您可能正在寻找的名称。

    【讨论】:

      【解决方案3】:

      另外,看看你的方法和绑定。您实际上使用了三种不同的方法来修复 handleProgress 函数的上下文。

      有关更多信息,请查看此答案:

      Can you explain the differences between all those ways of passing function to a component?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-28
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 2021-10-15
        • 1970-01-01
        • 2019-04-09
        • 2020-10-10
        相关资源
        最近更新 更多