在 React.js 中创建可重用的辅助函数

新手上路,请多包涵

我一直在为我最新的应用构建 React 组件。我知道我可以重用有助于保持代码 DRY 的组件。

我想知道我是否可以重用函数。我知道必须有办法。

现在我有三个组件使用密码验证功能。

 passwordValidation() {
  const length = this.state.password.length;
  if (length > 7) return 'success';
  else if (length > 4) return 'warning';
  else if (length > 0) return 'error';
}

我创建了一个帮助文件 - helpers.jsx 并添加了:

 export function passwordValidation() {
  const length = this.state.password.length;
  if (length > 7) return 'success';
  else if (length > 4) return 'warning';
  else if (length > 0) return 'error';
}

然后我将它导入到我的组件中

import { passwordValidation } from '../helpers.jsx'

当我尝试在我的构造函数中绑定“this”时,我不断收到错误“passwordValidation is not a function”。

如果我在输入标签中调用它,我会收到“无法读取未定义的属性状态”。

只是想看看我哪里出错了。如果我在我的班级中定义它并添加 this.passwordValidation = this.passwordValidation.bind(this) 一切正常。

如果这不是最佳实践,我会回到我正在做的事情,但我假设我应该能够导入函数以使生活更轻松,我的代码更清晰!

原文由 hancho 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 351
2 个回答

辅助函数不应依赖于调用它们的组件的上下文 (至少在我看来) 。如果您需要在函数中使用某些参数,将其传递给函数始终是更好的做法,因为它有助于提高可重用性。所有组件的状态属性键可能不同,如果您忘记为状态属性使用精确键,这可能会导致错误。

例如

export function passwordValidation(password) {
  const length = password.length;
  if (length > 7) return 'success';
  else if (length > 4) return 'warning';
  else if (length > 0) return 'error';
}

如果我像上面那样更改功能,我可以使用下面给出的所有示例。

 import { passwordValidation } from '/path/to/helper/functions.js';

console.log(passwordValidation(this.state.password));
console.log(passwordValidation(this.state.confirmPassword));
console.log(passwordValidation(this.props.password));
console.log(passwordValidation(someFetchedObject.user.password));

原文由 bennygenel 发布,翻译遵循 CC BY-SA 3.0 许可协议

您的导入和导出没问题。您使用 ES6 中的命名导出/导入。

我相信,问题在于尝试使用状态。有什么方法可以将使用密码验证的三个组件合并为一个?或者删除辅助函数中的状态引用并仅将密码作为参数传递?那应该可以正常工作。

原文由 callmeroot 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题