反应评论部分字符计数器



各位开发者好,

所以,我有这个问题与React,虽然我认为我要显示2000作为一个数字和一个整体的值,当我写在评论部分,数字改变为NaN。我尝试使用parseInt()为了把跨度变成一个数字,但什么也没发生…有什么建议吗?

代码如下:)

import React from "react";
import Header from "../Header";
import "./contact-form.css";
function characterCounter() {
let text = document.getElementById("message").value;
let textLength = text.length;
let counter = document.getElementById("characterCounter");
let counterNumber = parseInt(counter);
counter.textContent = counterNumber - textLength;
}
class ContactPage extends React.Component {
render() {
return (
<div>
<Header />
<h1>Contact.</h1>
<form action="" className="contact-form" id="contactForm">
<label>Your Name</label>
<input type="text" placeholder="First Name..." />
<label>Your Last Name</label>
<input type="text" placeholder="Last Name..." />
<label>Your Email</label>
<input type="text" placeholder="Email..." />
<label>Your comment</label>
<textarea
name=""
id="message"
cols="10"
rows="10"
placeholder="Hey..."
onKeyDown={characterCounter}
></textarea>
<span>
Max words <span id="characterCounter">2000</span>
</span>
<button id="buttonSubmitContact" type="submit">
Submit
</button>
</form>
</div>
);
}
}
export default ContactPage;

所以…你在用React,是吗?好吧,我将重写组件以React的方式解决问题

const MAX_CHARS = 2000
function ContactPage() {
const [charsLeft, setCharsLeft] = useState(0);
const updateCharsCount = ({target:{value}}) => {
setCharsLeft(MAX_CHARS - value)
}
return (
<div>
<Header/>
<h1>Contact</h1>
<form action="" className="contact-form" id="contactForm">
<label>Your Name</label>
<input type="text" placeholder="First Name..."/>
<label>Your Last Name</label>
<input type="text" placeholder="Last Name..."/>
<label>Your Email</label>
<input type="text" placeholder="Email..."/>
<label>Your comment</label>
<textarea
name=""
id="message"
cols="10"
rows="10"
placeholder="Hey..."
onChange={updateCharsCount}
></textarea>
<span>Max words {charsLeft}/{MAX_CHARS}</span>
<button id="buttonSubmitContact" type="submit">
Submit
</button>
</form>
</div>
);
}
export default ContactPage;

顺便说一下,我使用了功能组件而不是类组件,这是当前的方法

最新更新