我創建了一個反應組件,它顯示輸入欄位的標簽。由于標簽文本的長度可變,我試圖動態更改字體大小,以便文本適合固定大小的容器。
但是,不知何故,當函式被呼叫時,我的字體大小沒有更新,我不知道為什么。
這是我的代碼:
import React from "react";
class NewDrive extends React.Component {
constructor(props) {
super(props);
this.myOutputRef = React.createRef();
this.myOutputContainerRef = React.createRef();
this.size = 50 "px";
}
componentDidMount() {
const output = this.myOutputRef.current;
const outputContainer = this.myOutputContainerRef.current;
this.size = parseFloat(this.size) - 40 "px";
if (output.clientHeight >= outputContainer.clientHeight) {
this.componentDidMount();
}
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="input-wrapper">
<label ref={this.myOutputContainerRef}>
<div style={{ fontSize: this.size }} ref={this.myOutputRef}>
Gas cost
</div>
</label>
<input
type="text"
value={this.state.from}
onChange={this.handleChange}
/>
</div>
</form>
);
}
}
export default NewDrive;
我還嘗試通過類似的呼叫更新 fontzize,output.style.fonSize = ...但這也不起作用。
uj5u.com熱心網友回復:
變數this.size不是組件狀態的一部分。
嘗試編輯建構式
constructor(props) {
super(props);
this.state = {
size: 50 "px",
}
this.myOutputRef = React.createRef();
this.myOutputContainerRef = React.createRef();
}
然后通過 更新size變數this.setState({size: parseFloat(this.size) - 40 "px"}),最后,在渲染方法中更改訪問size變數的方式 -... style={{ fontSize: this.state.size }} ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364855.html
標籤:javascript css 反应
上一篇:引數總和
