错误码
import React, {Component} from "react";
import ReactDOM from "react-dom";
class App extends Component {
constructor(props) {
super(props);
this.DemoRenderer = function () {
return <div>DemoRenderer</div>;
};
}
customerRender = () => {
// I can use this here which is not the type of React.createElement
console.log(this.DemoRenderer); // can console the function
// However, there will be an error like the below.
// React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined
return <this.DemoRenderer />;
};
render() {
return (
<div>
hello
{this.customerRender()}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
当我将箭头函数重写为正常函数时,没有出现错误。
无差错码
constructor(props) {
// ...
this.customerRender = this.customerRender.bind(this);
}
customerRender() {
return <this.DemoRenderer />;
};
package.json喜欢下面的内容。
"dependencies": {
"react": "16.8.6",
"react-dom": "16.8.6",
"react-scripts": "3.0.1"
},
"devDependencies": {
"typescript": "3.3.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
我还将代码放入代码框中,但是,关于同一代码的代码框中没有出现错误。https://codesandbox.io/s/using-dot-notation-for-jsx-type-forked-ep2hhw?file=/src/index.js
发布于 2022-08-09 01:08:51
可能是的复制品。箭头函数采用其封闭的执行上下文中的这一特性。
ECMAScript中的类语法只是语法糖。如果您看一下定义构造函数和继承方法的经典方法,所发生的事情就更有意义了。
箭头函数采用其封闭的执行上下文中的这一特性。也就是说,它是在词汇上限定作用域的(基于函数在代码中出现的位置),而对于函数声明和表达式,这取决于函数的调用方式。
请考虑以下几点:
let globalObject = this;
function MyConstructor() {}
// arrowFn is global code, so its this is set to the global object
MyConstructor.prototype.arrowFn = obj => console.log(
`arrow function\n` +
`this === instance? ${this === obj}\n` +
`this === globalObject? ${this == globalObject}`
);
// Function expressions and declarations get their this
// from how they're called
MyConstructor.prototype.fnExpr = function(obj){
console.log(
`function expression\n` +
`this === instance? ${this === obj}\n` +
`this === globalObject? ${this == globalObject}`
);
};
function fnDeclaration(obj) {
console.log(
`function declaration\n` +
`this === instance? ${this === obj}\n` +
`this === globalObject? ${this == globalObject}`
);
}
MyConstructor.prototype.fnDeclaration = fnDeclaration;
let myObj = new MyConstructor();
myObj.arrowFn(myObj);
myObj.fnExpr(myObj);
myObj.fnDeclaration(myObj);
https://stackoverflow.com/questions/73288814
复制相似问题