在reactjs教程中,.bind(this)在ajax回调结束时有什么目的?没有它,代码是否正常工作?
data: JSON.stringify({text: text}),
success: function (data) {
this.setState({data: data});
}.bind(this),
Run Code Online (Sandbox Code Playgroud) 我有一个React组件
export default class Archive extends React.Component {
...
}
Run Code Online (Sandbox Code Playgroud)
componentDidMount和onClick方法部分使用相同的代码,除了参数的微小变化.
是否可以在组件类中创建一个函数,以便可以在组件的范围内重用它?
我正在研究一个反应应用程序,this当组件类有很多功能时,我发现必须绑定一些麻烦.
class Foo extends Component {
constructor(props){
super(props);
this.function1 = this.function1.bind(this);
this.function2 = this.function2.bind(this);
this.function3 = this.function3.bind(this);
}
function1() {
...
}
function2() {
...
}
function3() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更有效的方法来做到这一点?
我无法访问this.state组件内的函数.我已经在SO上找到了这个问题,并将建议的代码添加到我的构造函数中:
class Game extends React.Component {
constructor(props){
super(props);
...
this.state = {uid: '', currentTable : '', currentRound : 10, deck : sortedDeck};
this.dealNewHand = this.dealNewHand.bind(this);
this.getCardsForRound = this.getCardsForRound.bind(this);
this.shuffle = this.shuffle.bind(this);
}
// error thrown in this function
dealNewHand(){
var allCardsForThisRound = this.getCardsForRound(this.state.currentRound);
}
getCardsForRound(cardsPerPerson){
var shuffledDeck = this.shuffle(sortedDeck);
var cardsForThisRound = [];
for(var i = 0; i < cardsPerPerson * 4; i++){
cardsForThisRound.push(shuffledDeck[i]);
}
return cardsForThisRound;
}
shuffle(array) {
...
}
...
...
Run Code Online (Sandbox Code Playgroud)
它仍然无法正常工作.this.state.currentRound …
tsling引发错误:
第1行:模块内部不需要'use strict'(严格)
这是我的代码
"use strict";
function Foo() {}
Foo.prototype.sayHello= function () {
console.log("hello!");
}
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = {
Foo: Foo
};
}
Run Code Online (Sandbox Code Playgroud)
怎么修复这个错误?
边注
我的代码同时使用module和vanilla javascript.我只想"strict mode"用于香草javascript.
也许我可以使用
if (typeof module !== 'undefined') {
"use strict";
}
Run Code Online (Sandbox Code Playgroud)
strict mode仅启用vanilla javascript?
导入 React, { Component } from 'react'
类列扩展组件{构造函数(道具){超级(道具)
this.state={
message:'Hello'
}
}
changeMessage(){
this.setState=({
message:'Welcome'
})
}
render(){
return(
<div>
<div>{this.state.message}</div>
<button onClick={this.changeMessage}>Click</button>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
导出默认列