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') );
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于