LoginSignup
3
0

More than 3 years have passed since last update.

【Riot.js】propsとstate

Last updated at Posted at 2020-02-19

Riot.jspropsstateについてまとめていきます。
まずはコードと結果から。
* 環境構築についてはこちら

index.html

<!doctype html>

<html>
  <head>
    <title>Riot practice</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
  </head>

  <body>

    <app></app>

    <script src="app.riot" type="riot"></script>
    <script src="https://cdn.jsdelivr.net/npm/riot@4/riot+compiler.min.js"></script>

    <script>
      riot.compile().then(() => {
        riot.mount('app', {
          title: 'propsのタイトル',
        })
      })
    </script>
  </body>
</html>
app.riot
<app>
  <h3>{ props.title }</h3>

  <h3>{ state.title }</h3>

  <style>
     h3 { color: green }
  </style>

  <script>
    export default {
      onMounted() {
        console.log('マウントされました。')
        // this.state.title = 'stateのタイトル' DOMは更新されない
        this.update({
          title: 'stateのタイトル'
        })
      }
    }
  </script>
</app>

結果

スクリーンショット 2020-02-19 15.28.28.png

props

コンポーネントの初期プロパティを受け取けとっている。

  • immutable data (不変のデータ)
  • passed in from parent (親から渡される)
  • can't change it (変更不可)
  • can be defaulted & validated (デフォルト値の設定と検証が可能)

state

this.props 属性がフリーズされている間は、this.stateオブジェクトは完全に変更可能であり、手動または this.update()メソッドを使用して更新する。

  • mutable data (可変のデータ)
  • maintained by component (コンポーネントによって保持)
  • can change it (変更可)
  • should be considered private (プライベートであるべき)

カウントアプリの作成

ボタンを押したら1増えるという単純なアプリを作成する。
1増えるということは、状態が変わっている
よって、stateを使う。

app.riot

<app>
  <p>カウント:{ state.count }</p>
  <button onclick={ plusCount }>+1</button>

  <script>
    export default {
      state: {
        count: 0
      },
      plusCount() {
        this.update({
          //count: this.state.count++  なぜか増えない
          count: this.state.count += 1
        })
      }
    }
  </script>
</app>

stateで値を保持し、this.update()で1増やす。

補足
  • this.state.count++しても値は増えなかった。。。
  • plusCount()内にconsole.log(this)を置いた結果↓ スクリーンショット 2020-02-19 16.14.08.png
3
0
2

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
3
0