我知道,react hooks的全部要点是摆脱基于类的组件并提升功能组件。但是,有可能在react钩子中实现继承吗?
例如,在这里,我创建两个钩子。 1. useEmailFormatValidator,其验证输入(onChange)是否为有效的电子邮件格式。 2. useEmailSignupValidator继承了useEmailFormatValidator,但是扩展了它的功能,以验证发生(onBlur)事件时用户可以使用用户名。
它们的全部要点是useEmailFormatValidator可以以登录形式使用,而useEmailSignupValidator可以以注册形式使用。
下面是我的代码
useEmailFormatValidator
import { useState } from 'react';
export const useEmailFormatValidator = () => {
const [value, setValue] = useState('');
const [validity, setValidity] = useState(false);
const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const inputChangeHandler = event => {
setValue(event.target.value.trim());
if (regex.test(String(event.target.value.trim()).toLowerCase())) {
setValidity(true);
} else {
setValidity(false);
}
};
return { value: value, onChange: inputChangeHandler, validity };
};
useEmailSignupValidator
import { useState } from 'react';
import { useEmailFormatValidator } from "../auth";
export const useEmailSignupValidator = () => {
const [value, setValue] = useState('');
const [validity, setValidity] = useState(false);
const emailFormatValidator = useEmailFormatValidator();
const inputChangeHandler = event => {
emailFormatValidator.onChange(event);
setValue(emailFormatValidator.value);
setValidity(emailFormatValidator.validity);
};
const verifyUserNameExists = event => {
// Verify username is availble in back-end.
};
return { value: value, onChange: inputChangeHandler, onBlur: verifyUserNameExists, validity };
};
我运行测试时,以下内容无法按预期运行,并且未定义“值”和“有效性”。
const inputChangeHandler = event => {
emailFormatValidator.onChange(event);
setValue(emailFormatValidator.value);
setValidity(emailFormatValidator.validity);
};
反正自定义钩子中有继承吗?还是您如何重用代码,这是React挂钩的目的?
答案 0 :(得分:1)
这不是一个自定义的钩子,恕我直言。为什么不这样做呢?
const isValidEmail = email => {
const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return regex.test(email);
};
const MyComponent = () => {
const [inputVal, setInputVal] = useState('');
return(
<div>
<input
type='text'
name='my-input'
onChange={e => {
const email = e.target.value;
if(isValidEmail(email)){
setInputVal(email);
}else{
alert('invalid email')
}
}}
/>
</div>
)
}