【问题标题】:Calling props function inside component's function "Cannot read property 'props' of undefined"在组件的函数中调用道具函数“无法读取未定义的属性‘道具’”
【发布时间】:2018-12-24 10:59:39
【问题描述】:

我有一个按钮可以触发我的 onClick 功能:

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

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

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

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

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

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

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

一切正常。你知道如何解决这个问题吗?

【问题讨论】:

  • this.handleSubmit.bind(this, values) 这里的值是什么 btw bind 返回一个新函数,您需要将该函数存储在一个变量中然后调用它。您在构造函数中绑定它,并且再次在 onClick 中绑定。可以加完整代码吗?
  • 可以在这里添加完整的组件代码吗?
  • @vijayscode 值是来自用户的表单值数组。感谢您的意见!我会在进一步的函数声明中记住这一点。关于我的问题 - 现在一切正常

标签: javascript reactjs redux


【解决方案1】:

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

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

而不是

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

你还需要打电话给closeModal所以应该是

this.props.closeModal();

【讨论】:

  • 愚蠢的错误...我对 Formik 的所有功能和所有这些绑定感到困惑。非常感谢指出这个错误,感谢你展示了如何调用 props 函数,我之前没有这样做过
【解决方案2】:

改变你的构造函数,然后检查...

来自

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

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

【讨论】:

  • 好的,谢谢!我在你之前标记为答案帖子,因为@Amr Labib 还向我展示了如何在另一个函数中使用我的 props 函数
猜你喜欢
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
  • 2019-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多