Reactガイドを読んでいくその4
これは
Reactのガイドを読んでいく記事です
ガイドのリンク
コンポーネントと props
コンポーネントの概念の導入を行う章。
コンポーネントはJavaScriptの関数と似た概念を持つ
関数コンポーネントとクラスコンポーネント
JavaScriptの関数を書くことがコンポーネントを定義する最もシンプルな方法。
以下の例ではpropsオブジェクトを引数で受け取り、React要素を返すので有効なReactコンポーネントと言える。
function Welcom(props) {
return <h1>Hello, {props.name}</h1>;
}
コンポーネントの定義のためにES6クラスも使用可能
class Welcom extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
コンポーネントのレンダー
要素はユーザ定義のコンポーネントを表すことも可能。
const element = <Welcome name="Sara" />;
Reactがユーザ定義のコンポーネントを見つけた場合JSXの属性を単一のオブジェクトとしてコンポーネントに渡す。
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
//Welcome関数を呼び出し
const element = <Welcome name="Sara" />;
// Welcome関数の結果が入ったelementを描画
ReactDOM.render(
element,
document.getElementById('root')
);
コンポーネントを組み合わせる
Reactアプリではボタン、フォーム、ダイアログ、画面全てが共通してコンポーネントとして表現される。
例:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Zyaki" />
<Welcome name="Hash" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
コンポーネントの抽出
コンポーネントを小さなコンポーネントに分割する。
以下のようなコードの場合、ネストが深くなり見にくくなっています。
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
Docでは以下のように変更しています。
// 機能ごとに関数を作成して、読みやすく変更
function formatDate(date) {
return date.toLocaleDateString();
}
function Avatar(props) {
return (
<img
className="Avatar"
src={props.user.avatarUrl}
alt={props.user.name}
/>
);
}
function UserInfo(props) {
return (
<div className="UserInfo">
<Avatar user={props.user} />
<div className="UserInfo-name">{props.user.name}</div>
</div>
);
}
function Comment(props) {
return (
<div className="Comment">
<UserInfo user={props.author} />
<div className="Comment-text">{props.text}</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
const comment = {
date: new Date(),
text: 'I hope you enjoy learning React!',
author: {
name: 'Hello Kitty',
avatarUrl: 'https://placekitten.com/g/64/64',
},
};
ReactDOM.render(
<Comment
date={comment.date}
text={comment.text}
author={comment.author}
/>,
document.getElementById('root')
);
Props は読み取り専用
コンポーネントの宣言の方法にかかわらず、propsを変更してはいけない。
入力されたものを変更せず同じ入力に対して同じ結果を返す関数を純粋であるとReactは考える。
reactの全てのコンポーネントは自身のpropsに対して純関数のように振舞わなければならない。
今日はここまで。