具有以下组成部分:
import React, { useEffect, useState } from 'react';
import { TextareaTestIds } from '../utils/test-ids';
export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
maxLength?: number;
id: string;
}
export function Textarea({ id, maxLength = 200, ...props }: TexareaProps) {
const test = id;
const [count, setCount] = useState(0);
useEffect(() => {
const refElement = document.getElementById(test) as HTMLTextAreaElement;
if (refElement) {
setCount(refElement.value.length);
}
}, [test]);
return (
<div>
{count}
<textarea
id={id}
maxLength={maxLength}
{...props}
></textarea>
</div>
);
}
export default Textarea;这个组件返回一个文本区域,用户可以在其中写入一个输入,同时它还显示了引入字符的当前计数。
当第一次打开模态时,不管写了多少文本,显示的值都是0(计数值)。如果模式关闭并再次打开,则使用前面引入的文本计数更新该值。
是否有一种在写入时实时更新计数的方法?
发布于 2021-12-22 21:44:04
你可以这样做,
import React from "react";
export interface TexareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
maxLength?: number;
id: string;
}
export const Textarea = React.forwardRef(
({ id = "my-id", maxLength = 200, ...props }: TexareaProps) => {
const [value, setValue] = useState("");
const count = value.length;
return (
<div className="relative flex flex-col">
{count}
<textarea
{...props}
value={value}
maxLength={maxLength}
onChange={(event) => setValue(event.target.value)}
></textarea>
</div>
);
}
);
export default Textarea;或者如果你从道具中得到了价值,
export const Textarea = React.forwardRef(
({ id = "my-id", maxLength = 200, ...props }: TexareaProps) => {
const count = props.value.length;
return (
<div className="relative flex flex-col">
{count}
<textarea
{...props}
value={value}
maxLength={maxLength}
></textarea>
</div>
);
}
);https://stackoverflow.com/questions/70455325
复制相似问题