完全備忘録
読みにくいと思います。ごめんなさい。
class based componentの書き方基本
example.js
class Text extends React.Component {
render() {
return <p> {this.props.children}</p>;
}
}
React.render(<Text>Hello World</Text>, document.body);
ただ、コンポーネントの中に状態を保持する必要がない場合は'extends React.Component'は飛ばしても大丈夫。
stateless componentの書き方基本
sample.js
const Text = (props) => (
<p>{props.children}</p>
)
ReactDOM.render(
<Text>Hello World</Text>,
document.querySelector('#root')
);
使用方法
上で示したように適切なpropsのコードを返すstateless functional componentsを書くこともできる。propsのタイプをコントロールできなくなるわけではない。でファルトのpropsとタイプを記入できる。
Sample1 : propsのタイプを記入するのと一緒にデフォルトを定義するパターン
Sample2 : argumentsを記入するのと一緒にデフォルトを定義するパターン
sample1.js
import React, { Component, PropTypes } from 'react'
const Test = ({ children }) =>
<p>{children}</p>
Text.propTypes = { children: React.PropTypes.string };
Test.defaultProps = { children: 'Hello World' };
sample2.js
import React, { Component, PropTypes } from 'react'
const Test = ({ children = 'Hello World' }) =>
<p>{children}</p>
Text.propTypes = { children: React.PropTypes.string };
1よりも2のほうがおすすめ。
defaultPropsは文脈によって変化してしまうためpureではなくなってしまう。
argumentsに初期値を記入するパターンは文脈によって変化することがなく安定している。そのため2のほうがおすすめ!
Contextの使い方
contextのタイプをstateless functional component で定義したい場合
- 1. argumentの2つ目をつくる
- childContextTypes 必ずstaticにする。それにより子孫のコンポーネントにタイプが受け継がれることになる。 似ているのは'propTypes'。 static childContextTypes = { *** } をつかうとchildComponentのタイプを定義できる
- getChildContext proptypeのメソッド。コンテクストのオブジェクト。一度定義すると子孫に引き継がれる。状態が変化したり、コンポーネントが新しいpropsを受け取るたびに呼ばれる。 getChildContext() { *** }を使うとchildComponentのcontextを定義できる。
sample.js
// Functional stateless component
const Text = (props, context) => (
<p style={context}>props.children</p>;
);
Text.contextTypes = {
fontFamily: React.PropsTypes.string
};
class App extends React.Component {
static childContextTypes = {
fontFamily: React.PropTypes.string
}
getChildContext() {
return {
fontFamily: 'Helvetica Neue;
// そのコンポーネントの既定値を使いたいなら fontFamily: this.props.fontFamily
}
}
render() {
return <Text>Hello World</Text>;
}
}
child componentのタイプを親のコンポーネントで定義すると、そのあと派生して作られたchild componentに自然と情報が伝わる。そのためタイプを定義するのはparent componentのほう。childからparentに定義した情報は伝わらない。
遺伝子と同じだ。
親の遺伝子は子供に伝わるけど、子供の遺伝子は親に伝わらない。