3

A working WebpackBin can be found at link below,

https://www.webpackbin.com/bins/-Kibrw5tNNrsQpENUv_M

I have two components. Parent component pass a function to its child component via prop and child component's event handler invoke the passed in function via func.bind(null, num) to provide extra pre-set argument.

Why dummyFunc.bind(null, 666) works, should not bind make the newly created function this context become null? Hence, every this.setState should become undefined.


Parent Component Code,

import React from 'react'
import Component from './Component'

export default class Hello extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      foo: 2
    }

    this.foo = this.foo.bind(this)
  }

  foo(newValue) {
    this.setState({
      foo: newValue + this.state.foo
    })
    console.log(this.state.foo)
  }

  render() {
    return (
      <div>
        <h1>App</h1>
        <Component dummyFunc={this.foo} />
      </div>
    )
  }
}

Child Component Code,

import React from 'react'

const Component = ({dummyFunc}) => {
  return (
    <div>
      <button onClick={dummyFunc.bind(null, 666)}>BUTTON</button>
    </div>
  )
}

export default Component
XY L
  • 25,431
  • 14
  • 84
  • 143

1 Answers1

2

Why alert.bind(null, 666) works, should not bind make the newly created function this context become null?

It only changes the context of the function you're binding to: alert (and only for the newly created bound function). So inside the alert function the context would be changed, which is almost fine - since internally alert would not use the default context, but that's not constrained.

The purpose of that code is to partially apply the argument for the alert function - that is a number 666.

From that perspective it would be more semantically correct to use anonymous functions:

<button onClick={() => alert(666)}>BUTTON</button>

In your bin you:

this.foo = this.foo.bind(this)

So you have bound a context explicitly. After you do that every other .bind() does not change the context anymore (it is as per the standard).

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • I do understand your code sample at the end and that do make sense for me. However, the first part is not quite clear to me. I updated my question (see code block at the end of question). – XY L Apr 26 '17 at 02:41
  • @LiXinyang No, it should not be equivalent: browser's `alert` function has no connection with react and its `setState` at all. It's a function that shows a popup message, nothing more. – zerkms Apr 26 '17 at 02:44
  • I should never use `alert` as a function placeholder. Please see my update – XY L Apr 26 '17 at 02:46
  • @LiXinyang see the answer update. – zerkms Apr 26 '17 at 02:55