Creé un componente de reacción que muestra una etiqueta para un archivo de entrada. Dado que el texto de la etiqueta es de longitud variable, estoy tratando de cambiar dinámicamente el tamaño de la fuente para que el texto se ajuste al contenedor de tamaño fijo.
Sin embargo, de alguna manera mi tamaño de fuente no se actualiza cuando se llama a la función y no puedo entender por qué.
Aquí está mi código:
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; También intenté actualizar el fontzize con una llamada como output.style.fonSize = ... pero esto tampoco funcionó.
La variable this.size no es parte de un estado de componente.
Intenta editar el constructor.
constructor(props) { super(props); this.state = { size: 50 + "px", } this.myOutputRef = React.createRef(); this.myOutputContainerRef = React.createRef(); } luego actualice la variable de size por this.setState({size: parseFloat(this.size) - 40 + "px"}) , y por último, cambie en el método de representación cómo accede a la variable de size - ... style={{ fontSize: this.state.size }} ...