当我们想在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({})
“语法”。如果我必须回到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>
);
}
}
答案 0 :(得分:1)
关注your comment,这是this.state
初始化的问题。实际上,在getter中,您使用的是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;
}
答案 1 :(得分:1)
看起来你的ParentComponent的'clickMe'处理程序没有绑定到它的实例'this'。
您可以在此处执行此操作:
<span onClick={this.clickMe}>Click Me</span>
到
<span onClick={this.clickMe
的 .bind(本)强> }>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