0
class ImageGridList extends React.Component {
nodeRef = null
say = () => {
    console.log(this.nodeRef)
}
render() {
    let that = this;
    return (
        <div style={{height: '100px', width: '100px', border: '1px solid blue' }}
             onClick={this.say} ref={ node => this.nodeRef = node }
        />
    )
}

when you click, this.nodeRef is undefined. The 'this' object in say function not equal render function's this.

onClick={this.say.bind(this)} ref={ node => this.nodeRef = node }

will be ok!

constructor(props){
 super(props)
 this.say = this.say.bind(this)
}

undefined also. the .babelrc file is

{
  "presets": [
    "react",
    ["env", {
      "modules": false,
      "targets": {
        "browsers": [
          "last 1 Chrome versions"
        ],
        "node": "current"
      }
    }]
  ],
  "plugins": [
    "react-hot-loader/babel",
    ["transform-es2015-arrow-functions", {"spec": true}],
    ["transform-class-properties", { "spec": false }],
    "transform-object-rest-spread",
    ["transform-runtime", {
      "helpers": true,
      "polyfill": false,
      "regenerator": false
    }]
  ]
},

may be something wrong

gaoay
  • 1
  • 1

2 Answers2

0

Try to change this instance with that instance in this line:

onClick={this.say} ref={ node => this.nodeRef = node }

will be:

onClick={that.say} ref={ node => that.nodeRef = node }

Abe
  • 1,357
  • 13
  • 31
  • I hope to understand why. not how to resolve it. change arrow function with bind(this) will be ook. – gaoay Mar 05 '18 at 14:14
0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Arrow functions do not have their own this.
bind method binding your specified context to function, but: Can you bind arrow functions?