C#开发人员在这里。 我想问一下如何为一个类添加值。
这是我的课程:
class Players {
constructor(playerOne, playerTwo) {
this.playerOne = playerOne;
this.playerTwo = playerTwo;
}
}
在这里我称它为构造函数:
handleClick() {
this.setState({ clicked: true });
Players(
document.getElementById("Select_Player1").value,
document.getElementById("Select_Player2").value
);
console.log(Players.playerOne);
console.log(Players.playerTwo);
}
然后将其导出到文件末尾:
export { Players };
单击执行handleClick()
应用程序的按钮后,返回错误:TypeError: Cannot call a class as a function
。
答案 0 :(得分:1)
this.playerOne
和this.playerTwo
不是静态的!
因此可用于非静态:
class Players {
constructor(playerOne, playerTwo) {
this.playerOne = playerOne;
this.playerTwo = playerTwo;
}
}
var myP = new Players(
'test1',
'test2'
);
console.log(myP.playerOne);
console.log(myP.playerTwo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
并使用静态:
class Players {
static setPlayers(playerOne, playerTwo) {
this.playerOne = playerOne;
this.playerTwo = playerTwo;
}
}
Players.setPlayers(
'test1',
'test2'
);
console.log(Players.playerOne);
console.log(Players.playerTwo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>