Passing an additional parameter with an onChange event

前端 未结 7 892
生来不讨喜
生来不讨喜 2021-01-31 07:33

What I\'m trying to do:

I am trying to pass a string from a child component to the handleChange function of a parent component.

What cur

7条回答
  •  野性不改
    2021-01-31 07:51

    As the OP, I had originally posted this as a follow up on my question, but it was deleted and I was told to post it as an answer instead, so here it is:

    Based on Ritesh Bansal's answer, I have learned the following:

    The following line was not working because when using parenthesis after the function name, the function is called immediately rather than waiting for a change to happen:

    The above will not work, neither would a function such as this:

    The above would also get called immediately on first render.

    There are two solutions to this:

    The not-so good way:

    The much better way:

    this.props.handleChange("tags", evt)}>

    The problem is now solved. Thank you everyone!

    Update:

    I also researched Shubham Khatri's suggestion to change the child element to this:

     this.handleChange(e, val)}/>
    

    I did not realize that using bind in the render function, that every time render is called it creates a new function instance. I can, therefore, either use Shubham Khatri's method, or bind the methods in the constructor.

提交回复
热议问题