arrow-functions作为类属性,无法获取ref

问题描述 投票:0回答:2
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 }
        />
    )
}

单击时,this.nodeRef未定义。假设函数中的'this'对象不等于渲染函数。

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

会好的!

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

也未定义。 .babelrc文件是

{
  "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
    }]
  ]
},

可能是错的

javascript reactjs
2个回答
0
投票

尝试在此行中使用this实例更改that实例:

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

将会:

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


0
投票

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

箭头功能没有自己的功能。 绑定方法将指定的上下文绑定到函数,但是:Can you bind arrow functions?

© www.soinside.com 2019 - 2024. All rights reserved.