Renders a textarea component with a character limit.
- Use the
React.useState()
hook to create thecontent
state variable and set its value tovalue
.
Create a methodsetFormattedContent
, which trims the content of the input if it’s longer thanlimit
. - Use the
React.useEffect()
hook to call thesetFormattedContent
method on the value of thecontent
state variable. - Use a
<div>
to wrap both the<textarea>
and the<p>
element that displays the character count and bind theonChange
event of the<textarea>
to callsetFormattedContent
with the value ofevent.target.value
.
代码实现
function LimitedTextarea({ rows, cols, value, limit }) {
const [content, setContent] = React.useState(value);
const setFormattedContent = text => {
text.length > limit ? setContent(text.slice(0, limit)) : setContent(text);
};
React.useEffect(() => {
setFormattedContent(content);
}, []);
return (
<div>
<textarea
rows={rows}
cols={cols}
onChange={event => setFormattedContent(event.target.value)}
value={content}
/>
<p>
{content.length}/{limit}
</p>
</div>
);
}
使用样例
ReactDOM.render(<LimitedTextarea limit={32} value="Hello!" />, document.getElementById('root'));