Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda