【问题标题】:TextArea Auto resizeTextArea 自动调整大小
【发布时间】:2021-11-25 08:44:44
【问题描述】:

我想要实现的是一个 textarea,当用户继续键入或将长文本粘贴到文本区域时,它会自动调整大小。

这就是我所拥有的。

class TextArea extends InputBase {

    render() {
        const { label, placeholder, wrap, rows, cols, disabled, style, textStyle, textClass, value } = this.props;

        return (
            <div className={formClass} style={style}>
                {!!label && (<label className="control-label" htmlFor={this.id}>{label}</label>)}
                <textarea id={this.id} className={`form-control ${textClass}`} placeholder={placeholder} disabled={disabled} style={textStyle}
                    rows={rows} cols={cols} wrap={wrap} value={this.state.value || ''}
                    onChange={this.onChange} onBlur={this.onBlur} onFocus={this.onFocus} onKeyPress={this.onKeyPresses} onKeyUp={this.onKeyUp}>{value}</textarea>
            </div>
        );
    }
}

关于如何调整 textarea 大小的任何建议,以便它根据 textarea 中内容的长度进行扩展。

【问题讨论】:

标签: javascript reactjs frontend


【解决方案1】:

您可以使用outlined in css-tricks.com 的方法通过 CSS 解决这个问题。

解决方案是将您的textarea 放入一个 div 中,使您的 div 与textarea 的样式匹配,然后使用display:grid 使textarea 随着其增长而扩展以填充其父容器:

.grow-wrap {
  /* easy way to plop the elements on top of each other and have them both sized based on the tallest one's height */
  display: grid;
}

.grow-wrap::after {
  /* Note the weird space! Needed to preventy jumpy behavior */
  content: attr(data-replicated-value) " ";
  /* This is how textarea text behaves */
  white-space: pre-wrap;
  /* Hidden from view, clicks, and screen readers */
  visibility: hidden;
}

.grow-wrap>textarea {
  /* You could leave this, but after a user resizes, then it ruins the auto sizing */
  resize: none;
  /* Firefox shows scrollbar on growth, you can hide like this. */
  overflow: hidden;
}

.grow-wrap>textarea,
.grow-wrap::after {
  /* Identical styling required!! */
  border: 1px solid black;
  padding: 0.5rem;
  font: inherit;
  /* Place on top of each other */
  grid-area: 1 / 1 / 2 / 2;
}
<div class="grow-wrap">
  <textarea name="text" id="text" onInput="this.parentNode.dataset.replicatedValue = this.value"></textarea>
</div>

【讨论】:

    猜你喜欢
    • 2013-06-21
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多