Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
Passing a function to a Javascript class constructor

My code is as follows:

const [ fields, setFields ] = useState({
   fruit: 'default',
   cheese: 'default',
})

const handleChange = (newFields) => setFields({...fields, ...newFields})

let a = new Fruit('fruit', fields, handleChange, 'What kind of fruit do you like?')
let b = new Cheese('cheese', fields, handleChange, 'What is your favorite cheese?')

return (
   <div>
      {a}
      {b}
   </div>
)
...

The classes Fruit and Cheese are defined as follows:

class Fruit {

  constructor(name, fields, onChange, prompt) {
    this.name = name
    this.fields = fields
    this.onChange = onChange
    this.prompt = prompt
  }

  render() {
    return (
      <div>
        {this.prompt}
        <input
          name={this.name}
          value={this.fields[this.name]}
          onChange={(e)=>this.onChange({
             [this.name]: e.target.value
          }) }
        />
      </div>
    )
  }
}

The problem I'm having is that when the function this.onChange is called inside each class, it uses the value of fields that was set at the the constructor was called instead of the current value of fields. For example, if I enter 'apple' for fruit and then tried to enter 'cheddar' for cheese, the resultant fields will be {fruit: 'default', cheese: 'cheddar'}.

Is there a way to ensure that calling this.onChange will call the function outside the class (handleChange) which in turn will use the current copy of fields) ?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda