週末副業記

土日は副業エンジニアのブログです。副業に関することを投稿します。

React攻略への道のり[2日目][props]


f:id:aisakakun:20160824223221j:plain

Reactのチュートリアルは一通りやった(書いただけ)のですが、

propsがよく分からず試行錯誤。



ようやく使い方が分かってきたので、コードを載っけます。
prop:小道具
訳あってるのかな?  動きとしては、見てもらったほうが分かりやすそう。

まずは、propsを使う元となるところのコードは、こんな感じ。

var Comment = React.createClass({
  render: function() {
    return (
    <div>
      <h2>
        {this.props.author}
      </h2>
    </div>
    );
  }
});

(※[1]より引用)

そして、大本として出力する部分に、

<Comment author="Pepe Hunt" />

を挿入する。全体としてはこんな感じです。

<html>
<script src="https://fb.me/react-0.14.7.js"></script>
<script src="https://fb.me/react-dom-0.14.7.js"></script>
<script src="http://fb.me/JSXTransformer-0.13.3.js"></script>

<div id="module"></div>

<script type="text/jsx">
var Editor = React.createClass({
    getInitialState: function() {
        return {value: "Type Something here"};
    },
    handleChange: function() {
        this.setState({value: this.refs.textarea.value});
    },
    render: function() {
        return (
            <div className="Editor">
            <h3>Input</h3>
            <textarea
            onChange={this.handleChange}
            ref="textarea"
            defaultValue={this.state.value} />
            <h3>Output</h3>
            <div 
            dangerouslySetInnerHTML={{__html: this.state.value}}
            />
            <Comment author="Pepe Hunt" /> ←追加部分
            </div>
        );
    }
});

var Comment = React.createClass({
  render: function() {
    return (
    <div>
      <h2>
        {this.props.author}
      </h2>
    </div>
    );
  }
});

こうすると出力結果としてはこんな感じになります。
f:id:aisakakun:20160824222454p:plain

this.props.authorの"author"のところを適当に変えてみたり、
のauthorの部分を適当に変えたりしたら挙動が分かります。

propsは、別のところで決めた関数とかそういうのを別のところでも使えます〜
という感じと捉えています。
ちなみに、

<Comment author="Pepe Hunt" />
<Comment author="asasa" />

と適当に同じようなものを追加すると....
f:id:aisakakun:20160824223010p:plain
こうなる。
なるほど。

ちなみに、今回新しく追加した部分以外については、こちらをご覧ください。
infoaisaka.hatenablog.com

それでは。


参考URL:
[1]:Tutorial: Intro to React – React