0

C# developer here. I would like to ask how can I add a values to a class.

This is my class:

class Players {
    constructor(playerOne, playerTwo) {
    this.playerOne = playerOne;
    this.playerTwo = playerTwo;
    }
}

Here I call it's constructor:

handleClick() {
this.setState({ clicked: true });
Players(
  document.getElementById("Select_Player1").value,
  document.getElementById("Select_Player2").value
);
console.log(Players.playerOne);
console.log(Players.playerTwo);
}

And I export it at the end of file:

export { Players };

After clicking on button which execute handleClick() application return an error: TypeError: Cannot call a class as a function.

Pozzi Userpic
  • 347
  • 8
  • 30

1 Answers1

1

The this.playerOne and this.playerTwo isn't static!

so for use non static:

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>

And use static:

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>
morteza ataiy
  • 541
  • 4
  • 12
  • Done, thanks! Would you help me with how can I get the values from this class in different file? I've exported it with `export { Players };` and then imported with `import { Players } from "./Authentication";` and I want to call `playerOne` from this class. `console.log({ Players.playerOne });` doesn't work. – Pozzi Userpic Aug 29 '18 at 12:46
  • 1
    @Chyu try use "export default class Players" and "import Players". more info: https://stackoverflow.com/questions/33956201/how-to-import-and-export-components-using-react-es6-webpack anyway please accept my answer :) – morteza ataiy Aug 29 '18 at 12:51
  • That's better. But I still can't get `playerOne` or `playerTwo`. And it's set: https://imgur.com/1OIITcI – Pozzi Userpic Aug 29 '18 at 13:07
  • use static solution. – morteza ataiy Aug 29 '18 at 13:09
  • Solved. I've been using `console.log({ Players.playerOne })` instead of `console.log(Players.playerOne)`. – Pozzi Userpic Aug 29 '18 at 13:17