0

I am developing on class components, I have very large methods and I wanted to transfer them to a file, but I don’t know how to do it. Loss of context occurs

import { handleChange } from './methods';    

class Test extends Component {
  state = {number: 42}

  render() {
    const { number } = this.state;
    return(
      <MyComponent number={number} onChange={e => handleChange(e)} />
    );
  }

}

export default Test;

// method.js
export const handleChange = (e) => {
    console.log("this is:", this)
    const { data } = this.state;
    const { name, value, key} = e.target;

    this.setState({
        data: {
            ...data,
            [key]: data[key].set(name, value)
        }
    });
}

In the console this is: undefined Method should be outside the class. How fix?

Tims
  • 11
  • 1
  • Relevant: [How does the "this" keyword work?](https://stackoverflow.com/q/3127429) | [Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?](https://stackoverflow.com/q/34361379) – VLAZ Nov 23 '21 at 12:58
  • Pass the instance as an argument or using `.call()`. – Bergi Nov 23 '21 at 12:58
  • 3
    "*I have very large methods*" - instead of moving the large method to a separate file, break it down into smaller parts. Then move all the parts that *don't* have anything to do with the whole component directly to separate functions in a separate module. – Bergi Nov 23 '21 at 13:00
  • 1
    @Bergi thanks, run! `const handleChange = (e, self) => {` and `onChange={e => handleChange(e, this)` – Tims Nov 23 '21 at 13:34

0 Answers0