我为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,则该函数将被调用(如果您要调用某个函数),但是没有像预期的那样向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>
)
}
}发布于 2017-07-13 12:17:18
感谢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>
)
}
}https://stackoverflow.com/questions/45079800
复制相似问题