简体   繁体   English

动态更改字体大小以使文本适合容器

[英]Dynamically change font-size to fit text into container

I created a react componentn whicht displays a label for an input filed.我创建了一个反应组件,它为输入字段显示 label。 Since the label text is of variable length I am trying to dynamically change the font size in order for the text to fit into the fix sized container.由于 label 文本的长度可变,因此我试图动态更改字体大小以使文本适合固定大小的容器。

However, somehow my font-size does not get updated when the function gets called and I can not figure out why.但是,当调用 function 时,不知何故我的字体大小没有更新,我不知道为什么。

Here is my code:这是我的代码:

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;

I have also tried to update the fontzize with a call like output.style.fonSize =... but this did not work either.我还尝试使用output.style.fonSize =...之类的调用来更新 fontzize,但这也不起作用。

Variable this.size is not part of a state of component.变量this.size不是 state 组件的一部分。

Try editing the constructor尝试编辑构造函数

constructor(props) {
    super(props);
    this.state = {
        size: 50 + "px",
    }

    this.myOutputRef = React.createRef();
    this.myOutputContainerRef = React.createRef();
  }

then update the size variable by this.setState({size: parseFloat(this.size) - 40 + "px"}) , and lastly, change in the render method how you access the size variable - ... style={{ fontSize: this.state.size }}...然后通过this.setState({size: parseFloat(this.size) - 40 + "px"})更新size变量,最后,在渲染方法中更改访问size变量的方式 - ... style={{ fontSize: this.state.size }}...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM