D
D
danilr2019-09-21 15:26:58
JavaScript
danilr, 2019-09-21 15:26:58

How to generalize a method?

There are many fields that, when changed, write to the state - and each field has its own handler.
How to make one method take a parameter and understand where to write to the state?

handleChangeKpp = (kpp: string) => {
        this.setState({kpp});
    };

Here is the method that needs to be universalized, for example, it takes a parameter "name" and does setSatate({name}),
takes "position" and does setSatate({name})

Answer the question

In order to leave comments, you need to log in

3 answer(s)
H
hzzzzl, 2019-09-21
@danilr

handleChange = e => {
    this.setState({ [e.target.name]: e.target.value })
  }

....

 <input type="text" name="text1" onChange={this.handleChange} />
 <input type="text" name="text2" onChange={this.handleChange} />
 <input type="text" name="text3" onChange={this.handleChange} />

I
i1yas, 2019-09-21
@i1yas

Here is the method that needs to be universalized, for example, it takes a parameter "name" and does setSatate({name}),
takes "position" and does setSatate({name})

This will not work, you will have to explicitly pass the name of the parameter to the function.
setParam = (name: string, value: any) => {
   this.setState({ ...this.state, [name]: value });
}
...
setParam("position", ...);

ps In your code, setState is passed a new object with no previous state, is that how it should be? In my example I added...this.state

A
abberati, 2019-09-21
@abberati

Try final-form. Great library for those with lots of fields.
Everything you need is inside. Google the report about final-form in YouTube, on holy.js was.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question