2019-09-11
描述
渲染一个带有单词个数限制功能的 textarea 组件。
- 使用
React.useState()hook 创建content和wordCount状态变量,他们的值分别设为value和0 - 创建一个
setFormattedContent方法,使用String.prototype.split(' ')把输入的内容转换为一个单词数组并检查使用了Array.prototype.filter(Boolean)获取的length是否大于limit - 如果上一步获取的
length超出了limit,就对输入进行截断,否则返回原始输入,在以上两种情况中需对content和wordCount进行更新 - 使用
React.useEffect()hook 调用setFormattedContent方法,其参数为content状态变量 - 将
<textarea>元素和展示单词数的<p>元素使用<div>进行包裹,<textarea>绑定onChange事件,该事件调用参数为event.target.value的setFormattedContent方法
实现
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')
);
ME!
链滴