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
}]
]
},
可能有些不对劲
答案 0 :(得分:0)
尝试在此行中使用this
实例更改that
实例:
onClick={this.say} ref={ node => this.nodeRef = node }
将是:
onClick={that.say} ref={ node => that.nodeRef = node }
答案 1 :(得分:0)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
箭头功能没有自己的功能。
bind方法将指定的上下文绑定到function,但是:Can you bind arrow functions?