Javascript 如何显示ContentDiv中输入的字符数计数?
根据中的代码,我有以下React应用程序,它将在输入N个字符后突出显示用户输入的文本。这使用一个带有HTML元素的事件更改,并将“额外字符”放在一个样式化的范围内:Javascript 如何显示ContentDiv中输入的字符数计数?,javascript,html,reactjs,react-hooks,Javascript,Html,Reactjs,React Hooks,根据中的代码,我有以下React应用程序,它将在输入N个字符后突出显示用户输入的文本。这使用一个带有HTML元素的事件更改,并将“额外字符”放在一个样式化的范围内: import React, { useRef} from "react"; export default function App() { // create a custon contentEditable div const EditDiv = (props) => { let
import React, { useRef} from "react";
export default function App() {
// create a custon contentEditable div
const EditDiv = (props) => {
let textRef = useRef(null); // grab innerHTML
// on change event
const contentChange = (event) => {
let html = event.target.innerText; // inner text, no HTML tags
// users add input, no problem
// but once inner text length greater than the max length:
if (html.length > props.charLimitLength) {
// text before limit hit
let start = html.slice(0, props.charLimitLength);
// text after limit hit
let overlimit = html.slice(props.charLimitLength);
// style overlimit with span tag
overlimit = `<span style="background:${props.highlightColor}">${overlimit}</span>`;
//set text as innerHTML
textRef.current.innerHTML = start + overlimit
// set the cursor at the end of innerHTML; otherwise, cursor jumps to start
let range = document.createRange();
let selection = window.getSelection(); // represents the range of text selected by the user
range.setStart(textRef.current.lastChild, 1);
selection.removeAllRanges();
selection.addRange(range);
}
}
return <div>
Characters: {countChar}
<div ref={textRef} contentEditable onInput={contentChange}></div>
</div>
}
return (
<div>
<b> Enter text in the div here, max length 10: </b>
<EditDiv charLimitLength={10} highlightColor={"red"} />
</div>
)
}
但是在这种情况下,使用setCount(html.length)
即setCount(event.target.innerText.length)
不是一个选项,因为它超出了显示计数的范围,例如键入{count}个字符
我不知道该怎么做
就我更大的目标而言,我试图在这里重新创建Twitter角色计数功能:
280个字符后,文本高亮显示:
您可以使用状态变量跟踪字符计数,并在
contentChange
函数中对其进行更新
const[count,setCount]=useState(0)
const contentChange=(事件)=>{
const html=event.target.innerText
setCount(html.length)
if(html.length>props.charLimitLength){
setCount(props.charLimitLength-html.length)
//代码的其余部分
}
}
屏幕截图
文本长度小于最大长度(10)时的正字符计数
文本长度超过最大长度(10)时的负字符计数
你能解释一下你所说的设置计数(event.target.innerText.length)是什么意思吗?不是一个选项,因为它超出了显示计数的范围,例如,你键入了{count}个字符?@ArunKumarMohan我应该解释得更好。如果您尝试,则
setCount()
需要位于contentChange
中。但是它会删除innerHTML内容,为什么会删除这些内容呢?不确定我是否遗漏了什么。看看我的答案是否有用。谢谢!这是没有为我单击的部分setCount(props.charLimitLength-html.length)
现在看起来很明显。我只是没用钩子,别担心!很乐意帮忙。
const [count, setCount] = useState(0);