textarea不退缩

时间:2018-05-23 07:52:58

标签: reactjs height textarea

我让textarea按内容扩展。但是当我删除文本时,textarea不会收缩,因为删除文本时element.scrollHeight没有减少。我怎么能解决这个问题?如何使scrollHeight减少?

super(props);
    this.state = {
        backgroundColor: 'transparent',
        buttonIsHidden: 'none',
        maskIsHidden: true,
        scrollHeight: 0,
        height: 0
    }

}   
    handleChange = (e) => {
        this.setState({scrollHeight: e.target.scrollHeight});
        console.log(e.target.scrollHeight);
    }
    render() {
        return(
            <div>
            <div className="mask" onMouseDown={this.focusOutChangeColor} hidden={this.state.maskIsHidden}></div>
            <div className="CommentPlaceHolder" style={{backgroundColor: this.state.backgroundColor}}>
                <form id="form1">
                    <textarea 
                        style={{height: this.state.scrollHeight}}
                        onFocus={this.focusOnChangeColor} 
                        className={this.state.maskIsHidden ? 'comment':'focusedComment'} 
                        name="subject" 
                        placeholder="Write something.."
                        onChange={this.handleChange}>
                    </textarea>

1 个答案:

答案 0 :(得分:0)

如果您不反对使用第三方组件,那么react-textarea-autosize非常棒 - https://github.com/andreypopp/react-textarea-autosize

如果您仍想自己动手,可以在此处查看其源代码 https://github.com/andreypopp/react-textarea-autosize/blob/master/src/calculateNodeHeight.js