javascript - 在组件函数 "Cannot read property ' props' of undefined 中调用 props 函数”

标签 javascript reactjs redux

我有一个按钮可以触发我的 onClick 函数:

<button id="closeModal" variant="danger" onClick={ this.onClick }></button>

我的 onClick 绑定(bind)在构造函数中:

this.onClick = this.handleSubmit.bind(this);

然后我指定函数来调用两个函数:其中一个来自 props,另一个不是(这是 Formik 的函数)。

onClick(event) {
    this.handleSubmit.bind(this, values);
    this.props.closeModal;
}

错误Uncaught TypeError: Cannot read property '...' of undefined当我将 onClick 中的两个函数切换到不同位置时,它们是相同的。我希望按钮现在触发两个功能。以前,当我只有

<button id="closeModal" variant="danger" onClick={ this.props.closeModal }></button>

一切都好。您知道如何解决这个问题吗?

最佳答案

我认为你没有根据你的代码绑定(bind)正确的函数,我希望看到这样的东西

this.onClick = this.onClick.bind(this)

而不是

this.onClick = this.handleSubmit.bind(this)

您还需要调用closeModal,所以它应该是

this.props.closeModal();

关于javascript - 在组件函数 "Cannot read property ' props' of undefined 中调用 props 函数”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53912529/

相关文章:

javascript - 如何使用 webpack 的 worker loader 加载 web worker

reactjs - React/Redux - 在应用程序加载/初始化上调度操作

javascript - 自动完成从 API 获取数据

javascript - 如何将数组发送到模式以在 Laravel 5.5 Blade 中使用 in_array 作为复选框来设置选中属性?

reactjs - 为什么 React 生产构建无法在浏览器上运行?

javascript - 如何使用 YUI3 检测 HTML 元素的样式变化?

html - 来自网络的图像不显示

javascript - 如何使用 Redux-Saga 处理 fetch() 响应中的错误?

javascript - 随处定制 cors

javascript - 下拉列表显示所有元素,但无法选择