<td>元素内textarea点击事件无响应,多行内容无法交互问题排查
表格单元格内Textarea点击与编辑异常问题
我有一个包含6列的表格,其中某行单元格使用textarea元素展示并获取用户输入。当前textarea内容过长时会被截断并显示省略号,期望点击textarea时,其能展开适配全部内容并允许编辑。但实际遇到以下问题:
- 内容较长时,无法点击textarea中的换行文本行,文本光标无法出现在第一行之后,即使设置
rows={n}也无效 - 为textarea添加的
onClick事件仅在第一行内容上触发,怀疑表格单元格干扰了点击事件处理
该组件嵌套在<td>元素内,相关React代码如下:
function DescriptionColumnCell({ initialValue }: { initialValue: string }) { const [description, setDescription] = useState(initialValue); const [isFocused, setIsFocused] = useState(false); const textareaRef = useRef<HTMLTextAreaElement>(null); useEffect(() => { setDescription(initialValue); }, [initialValue]); useEffect(() => { adjustTextareaHeight(); }, [description]); const adjustTextareaHeight = () => { if (textareaRef.current) { textareaRef.current.style.height = 'auto'; textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`; } }; const handleFocus = () => { console.log('handleFocus'); setIsFocused(true); adjustTextareaHeight(); }; const handleChange = (event: ChangeEvent<HTMLTextAreaElement>) => { setDescription(event.target.value); }; const handleClick = (event: React.MouseEvent) => { console.log('event', event); adjustTextareaHeight(); }; const handleMouseDown = (event: React.MouseEvent) => { console.log('event', event); }; const handleOnClick = (event: React.MouseEvent) => { console.log('handleOnClick', event); event.stopPropagation(); setIsFocused(true); }; return ( <div className={`${styles['description-column-cell']} ${isFocused ? styles['focused'] : ''}`}> <div className={`${styles['input-element']}`} onClick={handleOnClick} > <textarea ref={textareaRef} onClick={handleClick} value={description} placeholder="description" onChange={handleChange} onFocus={handleFocus} rows={1} style={{ overflow: 'hidden' }} /> </div> </div> ); };
对应的CSS样式如下:
.description-column-cell { position: relative; height: 34px; .input-element { width: 100%; height: 34px; textarea { width: 100%; height: 34px; padding-block: 8px; padding-inline: 16px; font-size: var(--12px); line-height: var(--leading-normal); color: var(--text-primary); border: none; background-color: transparent; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; resize: none; display: block; } } &.focused { .input-element { width: 100%; position: absolute; top: 0; left: 0; z-index: 100; textarea { max-height: 200px; white-space: normal; overflow: auto; background-color: var(--background-primary); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); outline: 1px solid var(--border-tertiary); cursor: text; position: relative; z-index: 101; } } } }
UPDATE:移除.description-column-cell的position: relative后,组件会继承最近的position: relative元素(一个高度为24px的<ul>标签)的定位,此时textarea可正常注册事件,第二行悬停时显示文本光标,推测<td>元素存在样式问题。
UPDATE2:为.description-column-cell设置position: fixed后,textarea第二行可点击、显示文本光标并注册事件,但需设置宽度匹配父级<td>以避免超出表格范围。
内容的提问来源于stack exchange,提问作者M.Holmes
相关产品推荐
相关产品推荐

