[英]How to bind this to React ES6 getter and setter functions?
当我们想在ES6函数中使用this
,我们需要在构造函数中这样说。
export class MyComponent extends React.Component {
constructor(){
super();
this.myFunc = this.myFunc.bind(this);
}
myFunc(){
/*
Now inside this function, this is now referring to our
component. We can now access props, states, and refs
because we declared 'this.myFunc = this.myFunc.bind(this);'
in the constructor.
*/
}
}
但是有getter函数,我不能像使用常规函数那样使用相同的函数绑定“语法”:
get value(){
return this.state.oneOfMyValues;
/*
The above does not work. this.state is undefined, so is .refs,
so is .props, because 'this' is not the component itself.
*/
}
正如我所说,构造函数中的绑定值()不起作用:
constructor(){
super();
this.myFunc = this.myFunc.bind(this); // This works. It's a regular function.
this.value = this.value.bind(this);
/* No compilation errors for this code, but it doesn't work. The 'this'
inside the get value() function is still not the component.
*/
this.state = {};
/* as suggested, but this.state is still undefined from
inside get value().
*/
}
我不能在getter函数上使用箭头函数,就像我可以使用常规函数一样。
我们如何将一个getter(也可能是一个setter)函数绑定到组件,以便它内部的'this'引用组件? 尽可能地,我不想使用React.createClass({})
“syntax”。 如果我必须回到createClass方式,如果我们无法通过'this'访问我们的组件,那么能够在ES6中编写getter和setter函数的重点是什么?
用法这是parentcomponent.js
@import React from 'react';
@import { MyComponent } from './mycomponent.js';
export class ParentComponent extends React.Component {
clickMe = () => {
console.log(this.refs.myComponent.value);
/*
Does not return anything because the get value()
function of MyComponent has no access to its state,
props, etc.
*/
}
render(){
return(
<div className="parent-component">
<span onClick={this.clickMe}>Click Me</span>
<MyComponent ref="myComponent" />
</div>
);
}
}
在你的评论之后 ,这是一个this.state
初始化的问题。 实际上,在getter中,你正在使用this.state. oneOfMyValues
this.state. oneOfMyValues
然而this.state
没有定义。
然后,解决方案是在组件的构造函数内声明this.state = {}
。
constructor(){
super();
this.myFunc = this.myFunc.bind(this); // This works. It's a regular function.
// this.value = this.value.bind(this); <-- NO NEED
this.state = {} ; //⚠️
}
对于绑定,您可以在getter中记录this.constructor
,您将确保getter和setter不需要手动绑定。
get value(){
console.log(this.constructor.name) //🔮 Expect to log "MyComponent"
return this.state.oneOfMyValues;
}
看起来你的ParentComponent的'clickMe'处理程序没有绑定到它的实例'this'。
你可以在这里做:
<span onClick={this.clickMe}>Click Me</span>
至
<span onClick={this.clickMe
.bind(this) }>Click Me</span>
或者您可以在ParentComponent的构造函数中执行此操作:
export class ParentComponent extends React.Component {
constructor(props){
super(props);
this.clickMe = this.clickMe.bind(this);
}
...
}
@Felix Kling的JSfiddle在他说他的代码有效的时候阐明了这一点。 他绑定了他的clickMe,因此它有效。 jsfiddle.net/hxL51764
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.