首页 > 解决方案 > 为什么使用 setState 后内联高度值没有更新?

问题描述

目标:在输入/粘贴文本后动态增加textarea元素的高度值。height的值应与textarea的scrollHeight超过clientHeight后的值相匹配。

问题:样式属性继续反映高度的初始状态,即继承。

import ReactDOM from 'react-dom';

export class Textarea extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            height: 'inherit'
        };

        // This binding is necessary to make `this` work in the callback
        this.handleKeyUp = this.handleKeyUp.bind(this);
    }

    handleKeyUp = (event) => {
        if (event.target.scrollHeight > event.target.clientHeight) {
            let newHeight = `${event.target.scrollHeight}px`;
            this.setState({
                height: newHeight
            });
        }
    }

    render() {
        console.log(this.state)
        return (
            <div className="content_wrap">
                <textarea
                    id="json-textarea"
                    className="content_textarea"
                    onKeyUp={this.handleKeyUp}
                    style={this.state}

                ></textarea>                        
            </div>
        )
    }
}

标签: javascriptreactjs

解决方案


您需要指出height您所在州的属性

<textarea
    id="json-textarea"
    className="content_textarea"
    onKeyUp={this.handleKeyUp(this)}
    style={this.state.height}
>

推荐阅读