React 组件中“无法读取未定义的属性‘onClick’”

The*_*ner 1 reactjs reactstrap

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

<NanoButton type="button" onClick={() => Router.push('/about')}>About</NanoButton>
Run Code Online (Sandbox Code Playgroud)

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

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;
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*eau 7

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

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

constructor(props) {
  super(props);
  this.onClick = this.onClick.bind(this);
}
Run Code Online (Sandbox Code Playgroud)

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