Renders a textarea component with a word limit.
- Use the
React.useState()
hook to create thecontent
andwordCount
state variables and set their values tovalue
and0
respectively. - Create a method
setFormattedContent
, which usesString.prototype.split(' ')
to turn the input into an array of words and check if the result of applyingArray.prototype.filter(Boolean)
has alength
longer thanlimit
. - If the afforementioned
length
exceeds thelimit
, trim the input, otherwise return the raw input, updatingcontent
andwordCount
accordingly in both cases. - 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 LimitedWordTextarea({ rows, cols, value, limit }) {
const [content, setContent] = React.useState(value);
const [wordCount, setWordCount] = React.useState(0);
const setFormattedContent = text => {
let words = text.split(' ');
if (words.filter(Boolean).length > limit) {
setContent(
text
.split(' ')
.slice(0, limit)
.join(' ')
);
setWordCount(limit);
} else {
setContent(text);
setWordCount(words.filter(Boolean).length);
}
};
React.useEffect(() => {
setFormattedContent(content);
}, []);
return (
<div>
<textarea
rows={rows}
cols={cols}
onChange={event => setFormattedContent(event.target.value)}
value={content}
/>
<p>
{wordCount}/{limit}
</p>
</div>
);
}
使用样例
ReactDOM.render(
<LimitedWordTextarea limit={5} value="Hello there!" />,
document.getElementById('root')
);