LoginSignup
2
0

More than 3 years have passed since last update.

Reactで作る「令和」パズル

Last updated at Posted at 2019-05-18

背景

仕事で使うので、Reactの勉強がてらパズルを作ってみた。
話題の「令和」と「平成」を使ったやつ…(すでにちょっと遅い感じも…)

完成品

下記のようなものができました。
スタートを押すと開始され、「令和」で揃えると完了!

See the Pen reiwa puzzle by hashito (@hashito) on CodePen.

TODO(残課題)

  • ウィンドウを小さくすると正しく表示されない
  • HTMLからの定義をもらってlevelやら大きさを可変させたい
  • もう少し…コードを整理したい

詰まった所

thisstateが参照できない。

下記のようなコードで何度確認してもthis.stateが定義されていない!

class Puzzle extends React.Component {
  constructor(props) {
    super(props);
    ....
  render() {
    return (
      <span
        className="puzzle"
        cal={this.state.y}

解決

コンストラクタでthis.render=this.render.bind(this);がされていない…
はい、ドキュメントを読みましょうってことですね。

class Puzzle extends React.Component {
  constructor(props) {
    super(props);
    this.render=this.render.bind(this);
    ....
  render() {
    return (
      <span
        className="puzzle"
        cal={this.state.y}

renderが呼び出されない

コンストラクタで受け取ったpropsを下記のようにstateに直接引き渡しをしていた。
コンストラクタはインスタンス生成時にしか呼び出されなかった…

class Puzzle extends React.Component {
  constructor(props) {
    super(props);
    this.state= props;
    ....
  render() {
    return (
      <span
        className="puzzle"
        cal={this.state.y}

下記のように改善…
しかし、更新されず…

class Puzzle extends React.Component {
  constructor(props) {
    super(props);
    this.state.y {y:props.y};
    ....
  render() {
    return (
      <span
        className="puzzle"
        cal={this.state.y}

解決

純粋にそのままpropsを見ればよかったのだ…

class Puzzle extends React.Component {
  constructor(props) {
    super(props);
    ....
  render() {
    return (
      <span
        className="puzzle"
        cal={this.props.y}

感想

Reactは結構「こうしてください!」ってのが多い感じがした。
書き方やロジックが矯正されるので誰が書いても同じようなコードになるのが利点なのかな…
オブジェクト構成とかも…

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0