"Cannot read property 'onClick' of undefined" 在 React 组件中

"Cannot read property 'onClick' of undefined" in React component

我在我的项目中使用 Reactstrap 进行 Bootstrap 集成。但是,我还需要扩展使用 Reactstrap 开箱即用的 Button 组件的 onClick 行为。为此,我制作了一个自定义 NanoButton 组件来重组默认组件。我是这样称呼它的:

<NanoButton type="button" onClick={() => Router.push('/about')}>About</NanoButton>

正如我所说,NanoButton 组件将我的自定义 onClick 功能添加到现有的 Button class:

import { Component } from 'react';
import { Button } from 'reactstrap';

class NanoButton extends Component {
  constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
  }
  onClick(e) {
        var circle = document.createElement('div');
        e.target.appendChild(circle);
        var d = Math.max(e.target.clientWidth, e.target.clientHeight);
        circle.style.width = circle.style.height = d + 'px';
        var rect = e.target.getBoundingClientRect();
        circle.style.left = e.clientX - rect.left -d/2 + 'px';
        circle.style.top = e.clientY - rect.top - d/2 + 'px';
        circle.classList.add('ripple');

        this.props.onClick();
  }
  render() {
    return (
      <Button
        className={this.props.className}
        type={this.props.type}
        color={this.props.color}
        size={this.props.size}
        onClick={this.onClick}
      >
        {this.props.children}
      </Button>
    );
  }
}

export default NanoButton;

如您所见,在最终执行作为 prop 传递给它的 onClick 函数之前,我需要 NanoButton 组件执行一些自定义活动。但是在浏览器中加载时,它在 this.props.onClick(); 处失败,说它无法读取 onClick on undefined?我在这里可能会遗漏什么?

您的 onClick 方法未绑定到您的 class 上下文,因此无法访问 this.props.

通常的解决方案是在构造函数中绑定此方法:

constructor(props) {
  super(props);
  this.onClick = this.onClick.bind(this);
}

另一种选择是按照建议在渲染方法中绑定,但这意味着绑定将在每次渲染时完成,而不是仅使用构造函数解决方案一次性完成。

如果您想忘记何时绑定或不绑定您的方法,您可以替换以下样式:

onClick(e) {

}

与:

onClick = (e) => {
  this.props.onClick();
}

并且箭头函数会自动为你绑定所有的东西,你不需要只改变你定义这些方法的代码。

onClick on undefined错误的原因是因为确实在缺少onClick方法定义的Dom元素的范围内定义了onClick。

this 未在函数 context 中定义时会发生这种情况,因此为了解决这个问题,您只需绑定此操作,因此您可以绑定this 要么在你的构造方法中,要么你可以直接将 this 与函数绑定,只要它在渲染函数中作为道具传递。

直接在构造函数中绑定

constructor(props){
 super(props);
 this.onClick = this.onClick.bind(this);
}

作为道具传递:-

<Button onClick={this.onClick.bind(this)/>