Reactjs 将onChange脚本添加到React中的输入框
我目前有一个输入框组件,我想添加一个脚本来阻止除数字以外的所有输入Reactjs 将onChange脚本添加到React中的输入框,reactjs,typescript,Reactjs,Typescript,我目前有一个输入框组件,我想添加一个脚本来阻止除数字以外的所有输入 function onChangeHandler(e: React.ChangeEvent) { this.value.replace(/(?![0-9])./gmi,''); } export function Input(props: InputProps) { const { className, ...restProps } = props; return ( <inpu
function onChangeHandler(e: React.ChangeEvent) {
this.value.replace(/(?![0-9])./gmi,'');
}
export function Input(props: InputProps) {
const {
className,
...restProps
} = props;
return (
<input
{...restProps}
className={cx([inputStyles])}
type={inputType}
onChange={e => onChangeHandler(e)}
/>
);
}
函数onChangeHandler(e:React.ChangeEvent){
此.value.replace(/(?![0-9])/gmi,”;
}
导出函数输入(props:InputProps){
常数{
类名,
…其他道具
}=道具;
返回(
onChangeHandler(e)}
/>
);
}
当前此设置不起作用,因为我从onChangeHandler
中得到以下错误:'this'隐式地具有类型“any”,因为它没有类型批注。
我怎样才能做到这一点
注意:我不想使用
type=number
当不存在任何作用域时,您试图访问此作用域。它不是一个类,它是一个函数,这里不需要这个
您的代码应该是这样的(不过,您可以将value
状态移动到父组件并通过道具传递):
导出函数输入(props:InputProps){
const[value,setValue]=React.useState(“”);
常数{
类名,
…其他道具
}=道具;
const onChangeHandler=(e:React.ChangeEvent)=>{
设置值(如目标值替换(/(?![0-9])/gmi,);
}
返回(
);
}
export function Input(props: InputProps) {
const [value, setValue] = React.useState('');
const {
className,
...restProps
} = props;
const onChangeHandler = (e: React.ChangeEvent) => {
setValue(e.target.value.replace(/(?![0-9])./gmi,''));
}
return (
<input
{...restProps}
className={cx([inputStyles])}
type={inputType}
value={value}
onChange={onChangeHandler}
/>
);
}