我有一个简单的textarea
React组件,可以在用户输入时增加其大小。该函数如下所示:
changeHeight(e) {
const height = this.textarea.clientHeight;
const scrollHeight = this.textarea.scrollHeight;
if (height < scrollHeight) {
this.textarea.style.height = scrollHeight + "px";
}
}
当我使用onKeyUp
在textarea上调用此函数时,它可以正常工作,但是如果我将其更改为onPaste
则会调用该函数(如果你调试.log某些东西),但没有高度按预期添加到textarea。
我有什么明显的遗漏吗?
这里是完整的代码:
class Textarea extends React.Component {
constructor(props) {
super(props);
this.changeHeight = this.changeHeight.bind(this);
}
changeHeight(e) {
const height = this.textarea.clientHeight;
const scrollHeight = this.textarea.scrollHeight;
if (height < scrollHeight) {
this.textarea.style.height = scrollHeight + "px";
}
console.log("changeHeight");
}
render() {
const {input, label, type, optional, value, helperText, meta: { touched, error }, ...custom } = this.props;
return (
<div className="measure mb4">
<label for="name" className="f6 b db mb2">{label} {optional ? <span className="normal black-60">(optional)</span> : null}</label>
<textarea onPaste={this.changeHeight} ref={(el) => { this.textarea = el; }} className={"input-reset ba b--black-20 pa2 mb2 db w-100 border-box lh-copy h5 animate-h"} aria-describedby="name-desc" {...input} {...custom} value={value} />
{touched && error ? <small id="name-desc" className="f6 red db mb2">{error}</small> : null}
{helperText ? <small id="name-desc" className="f6 black db mb2">{helperText}</small> : null}
</div>
)
}
}
答案 0 :(得分:0)
感谢Teemu在评论中发布答案:
将事件更改为onInput
按预期工作(当用户键入和粘贴时触发事件)。更新的代码:
class Textarea extends React.Component {
constructor(props) {
super(props);
this.changeHeight = this.changeHeight.bind(this);
}
changeHeight(e) {
const height = this.textarea.clientHeight;
const scrollHeight = this.textarea.scrollHeight;
if (height < scrollHeight) {
this.textarea.style.height = scrollHeight + "px";
}
console.log("changeHeight");
}
render() {
const {input, label, type, optional, value, helperText, meta: { touched, error }, ...custom } = this.props;
return (
<div className="measure mb4">
<label for="name" className="f6 b db mb2">{label} {optional ? <span className="normal black-60">(optional)</span> : null}</label>
<textarea onInput={this.changeHeight} ref={(el) => { this.textarea = el; }} className={"input-reset ba b--black-20 pa2 mb2 db w-100 border-box lh-copy h5 animate-h"} aria-describedby="name-desc" {...input} {...custom} value={value} />
{touched && error ? <small id="name-desc" className="f6 red db mb2">{error}</small> : null}
{helperText ? <small id="name-desc" className="f6 black db mb2">{helperText}</small> : null}
</div>
)
}
}