背景介绍
正如我们所知道的 textarea 是一个行内块元素 display: inline-block 并且它的默认宽高由 cols & rows 决定, 也就是说 textarea 的 height 并不会自适应于内容长度.
那么, 我们今天的任务就是来思考如何创建一个 高度内容自适应的 textarea 组件,我将介绍三种思路实现 高度内容自适应的 textarea,具体代码 textareaAutoSizeSolutions
方案概要
这是三种方案的概述和实现思路的简介, 实现方案 & 遇到的坑 & 拓展知识点, 点击查看 teeeemoji 的 demo.
方案一: 两次调整 textarea.style.height
textarea 的 onchange 触发 resize 方法,下面是 resize 方法的逻辑textarea.style.height = 'auto';// 1. 让 textarea 的高度恢复默认
textarea.style.height = textarea.scrollHeight + 'px';// 2. textarea.scrollHeight 表示 *textarea* 内容的实际高度
方案二: 利用一个 ghostTextarea 获得输入框内容高度, 再将这个高度设置给真实的 textarea
textarea 构建时创建 ghostTextarea, onchange 触发 resize 方法:创建 textarea 的时候, 同时创建一个一模一样的隐藏 ghostTextarea;
ghostTextarea 的属性全部克隆自 textarea, 但是 ghostTextarea 是 隐藏 的, 并且 ghostTextarea.style.height = 0; 也就是说 ghostTextarea.scrollHeight 就是 textarea 中内容的真是高度。
resize 方法处理流程:textarea.value 先设置给 ghostTextarea,
拿到 ghostTextarea.scrollHeight
将 textarea.style.height = ghostTextarea.scrollHeight
方案三: 使用 (div | p | ...).contenteditable 代替 textarea 作为输入框
div 是块级元素, 高度本身就是内容自适应的(除非设置 max-width or min-widht) 使用 contenteditable 让 div 代替 textarea, 省去各种计算高度的逻辑。
方案对比
满分3分, 三种方案通过优化, 在用户体验和兼容性上都能达到满分. 因此差别仅仅在于这几个方案的实现难度. (仅仅是基于 react 组件的实现复杂度). 方案对比:
毫无疑问方案一是最优选择, 多加1分以示奖励;
方案一两次调整 textarea.style.height
实现思路渲染一个 textarea 元素
ref={this.bindRef}
className={style['textarea'] + ' ' + className}
placeholder={placeholder}
value={value}
onChange={