javascript - 为什么使用 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>
)
}
}
解决方案
您需要指出height
您所在州的属性
<textarea
id="json-textarea"
className="content_textarea"
onKeyUp={this.handleKeyUp(this)}
style={this.state.height}
>
推荐阅读
- html - 无边框后如何删除剩余空间
- azure-devops - 是否可以批准来自微软团队中 azure repos 的拉取请求?
- asp.net-mvc - 在两个日期之间作为 where 条件以及 Linq 中的 GETALL() 方法
- javascript - 如何正确获取输入数据并在函数中调用?
- graphviz - 如何在 Graphviz 中划掉一个节点?
- r - 根据分组和索引汇总一列中的值
- vuejs2 - 根据选择选项值过滤 Vue 列表
- javascript - 非顺序事件冒泡 onClick vs addEventListener
- graph - 在自然语言处理中使用图进行文本分类
- pandas - 在与其他数据框的多个匹配条件后将值分配给新的 df 列