我想要实现的是一个文本区域,它从单行开始,但会增长到 4 行,如果用户继续键入,此时开始滚动。我有一个部分解决方案有点工作,它增长然后在达到最大值时停止,但如果你删除文本它不会像我想要的那样收缩。
这就是我目前所拥有的。
export class foo extends React.Component {
constructor(props) {
super(props);
this.state = {
textareaHeight: 38
};
}
handleKeyUp(evt) {
// Max: 75px Min: 38px
let newHeight = Math.max(Math.min(evt.target.scrollHeight + 2, 75), 38);
if (newHeight !== this.state.textareaHeight) {
this.setState({
textareaHeight: newHeight
});
}
}
render() {
let textareaStyle = { height: this.state.textareaHeight };
return (
<div>
<textarea onKeyUp={this.handleKeyUp.bind(this)} style={textareaStyle}/>
</div>
);
}
}
显然,问题是当 height
设置为更大的值时,scrollHeight
不会缩小。关于如何解决此问题的任何建议,以便在删除文本后它也会缩小?
最佳答案
另一个简单的方法(没有额外的包)
export class foo extends React.Component {
handleKeyDown(e) {
e.target.style.height = 'inherit';
e.target.style.height = `${e.target.scrollHeight}px`;
// In case you have a limitation
// e.target.style.height = `${Math.min(e.target.scrollHeight, limit)}px`;
}
render() {
return <textarea onKeyDown={this.handleKeyDown} />;
}
}
删除文字后textarea不缩回的问题是忘记设置这一行
e.target.style.height = 'inherit';
考虑使用 onKeyDown,因为它适用于所有键,而其他键可能不适用 (w3schools)
如果您有 padding
或 border
的 top
或 bottom
。 ( reference )
handleKeyDown(e) {
// Reset field height
e.target.style.height = 'inherit';
// Get the computed styles for the element
const computed = window.getComputedStyle(e.target);
// Calculate the height
const height = parseInt(computed.getPropertyValue('border-top-width'), 10)
+ parseInt(computed.getPropertyValue('padding-top'), 10)
+ e.target.scrollHeight
+ parseInt(computed.getPropertyValue('padding-bottom'), 10)
+ parseInt(computed.getPropertyValue('border-bottom-width'), 10);
e.target.style.height = `${height}px`;
}
希望这对您有所帮助。
关于javascript/react 动态高度文本区域(停在最大值处),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39401504/