sumakokima2 / resium-sample2

0 stars 0 forks source link

ピンの作成: stateで管理 #27

Open sumakokima2 opened 4 years ago

sumakokima2 commented 4 years ago

今回は前回作ったピンをreactのstateを用いて書いていきます。 参考:https://ja.reactjs.org/docs/state-and-lifecycle.html

クラスコンポーネントしてカプセル化します

  1. React.Component を継承する同名の クラスを作成する。
  2. render() と呼ばれる空のメソッドを 1 つ追加する。
  3. 関数の中身を render() メソッドに移動する。

せっかくなのにApp.jsも。

class App extends React.Component {
  render() {
    return (
     <Viewer full>
      <Entity1 />
      </Viewer>
    );
  }
}

Entity.js

const position = Cartesian3.fromDegrees(-74.0707383, 40.7117244, 100);
const pointGraphics = { pixelSize: 10 };
const description="<h1>Hello, world.</h1><p>thanks</p>";
const label = {text:"label", scale: 3, fillColor: Color.PINK};

class Entity1 extends React.Component {
  render() {
    return (
     <Entity position={position} point={pointGraphics} name={name} description={description} label={label}/>
    );
  }
}

クラスにローカルなStateを追加する

  1. this.stateの初期状態を設定するクラスコンストラクタを追加する(*クラスのコンポーネントは常に props を引数として親クラスのコンストラクタを呼び出す必要があります。)
  2. render()メソッド内のconstthis.state.XXX に書き換える
  3. 上の作業が終わったらconst を削除
import React from 'react';
import { hot } from "react-hot-loader/root";
import { Viewer, Entity } from 'resium';
import { Cartesian3, Color } from 'cesium';

//const position = Cartesian3.fromDegrees(-74.0707383, 40.7117244, 100);  ③
//const pointGraphics = { pixelSize: 10 };  ③
//const description="<h1>Hello, world.</h1><p>thanks</p>";  ③
//const label = {text:"label", scale: 3, fillColor: Color.PINK};  ③

class Entity1 extends React.Component {

    constructor(props) {        ①クラスコンストラクタ
      super(props);   ①propsに注目
      this.state = {name: "Tokyo1",   ①stateにデータを入れていく!
                    position:Cartesian3.fromDegrees(-74.0707383, 40.7117244, 100),
                    pointGraphics : { pixelSize: 10 },
                    description:"<h1>Hello, world.</h1><p>I tried STATE</p>",
                    label : {text:"STATE", scale: 3, fillColor: Color.PINK}

      };
    }

  render() {
    return (   ②this.state.XXX の要領でstateデータを読み込む
            <Entity position={this.state.position} point={this.state.pointGraphics} name={this.state.name} description={this.state.description} label={this.state.label}/>
    );
  }
}

export default hot(Entity1);

スクリーンショット 2020-03-10 23 50 45

おしまい!