问题描述
我正在使用React.js,我希望输入文本适合它的容器,但是要onChange。
例如:如果用户输入“ T”
然后他输入'E',所以现在输入的是'TE'
请帮助我吗?感谢在广告中..:)
解决方法
我创建了一个小应用程序对此进行演示。我正在使用两种状态text
来管理文本框中的当前文本,并使用一种状态fontSize
来计算文本的当前字体大小。我将上限设置为200px,将下限设置为50px,以使文本看起来不会太大或太小。比率为1.2
,这意味着每当有人添加新字符时,文本大小将增加到1.2,并且如果删除字符,则大小将减少1.2。这是一个应用程序。
import React,{ useState,useCallback } from "react";
export default function App() {
const [fontSize,setFontSize] = useState(200);
const [text,setText] = useState("");
const updateFontSize = useCallback(
(value) => {
if (text.length > value.length) {
const textSize = Math.ceil(fontSize * 1.5,10);
fontSize < 200 && setFontSize(textSize);
} else if (text.length < value.length) {
const textSize = Math.ceil(fontSize / 1.5,10);
fontSize > 50 && setFontSize(textSize);
}
setText(value);
},[fontSize,text]
);
return (
<div className="App">
<input
type="text"
onChange={(event) => updateFontSize(event.target.value)}
/>
<div style={{ fontSize: `${fontSize}px` }}>{text}</div>
</div>
);
}
这里是一个代码沙箱link,供您参考。