han*_*cho 2 javascript reactjs redux
我一直在为我的最新应用程序构建React组件.我知道我可以重复使用有助于保持代码干净的组件.
我想知道我是否可以重用功能.我知道必须要有办法.
现在我有三个使用密码验证功能的组件.
passwordValidation() {
const length = this.state.password.length;
if (length > 7) return 'success';
else if (length > 4) return 'warning';
else if (length > 0) return 'error';
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个帮助文件--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';
}
Run Code Online (Sandbox Code Playgroud)
然后我将它导入我的组件
import { passwordValidation } from '../helpers.jsx'
Run Code Online (Sandbox Code Playgroud)
当我尝试在我的构造函数中绑定"this"时,我不断收到错误"passwordValidation is a function".
如果我在输入标记中调用它,我将"无法读取未定义的属性状态".
只是想看看我哪里出错了.如果我在课堂上定义并添加,一切都有效this.passwordValidation = this.passwordValidation.bind(this).
如果这不是最佳实践,我会回到我正在做的事情,但我假设我应该能够导入函数以使生活更轻松,我的代码更清晰!
辅助函数不应该依赖于它们被调用的组件的上下文(至少在我看来).如果你需要在函数中使用一些参数,那么函数总是更好的做法,因为它有助于重用性.对于所有组件,state属性的键可能不同,如果您忘记对state属性使用确切键,则可能会导致错误.
例如
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';
}
Run Code Online (Sandbox Code Playgroud)
如果我改变上面的功能,我可以使用下面给出的所有示例.
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));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4364 次 |
| 最近记录: |