Reactガイドを読んでいくその51
これは
Reactのガイドを読んでいく記事です。
ガイドのリンク
他のライブラリとのインテグレーション
Model 層とのインテグレーション
一般的にReactのstate、Flux、Reduxのような一方向のデータフローの使用が推奨されるが、Reactコンポーネントはほかのフレームワークやライブラリのモデル層を利用することが可能。
React コンポーネントで Backbone Model を使用する
Backboneモデルとコレクションを最も簡単に利用する方法は様々な変更イベントを監視して手動で強制的に更新すること。
下の例では、ListコンポーネントはBackbbornのコレクションをレンダーし、個別要素のレンダーにはItemコンポーネントを使用する。
それぞれ責任を持つコンポーネントはイベントを監視しており、this.forceUpdate()
を呼び出して新しいデータでコンポーネントを再レンダリングする。
class Item extendos React.Componen { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); } handleChange() { this.forceUpdate(); } componentDidMount() { this.props.model.on('change', this.handleChange); } componentWillUnmount() { this.props.model.off('change', this.handleChange); } render() { return <li>{this.props.model.get('text')}</li>; } } class List extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); } handleChange() { this.forceUpdate(); } componentDidMount() { this.props.collection.on('add', 'remove', this.handleChange); } componentWillUnmount() { this.props.collection.off('add', 'remove', this.handleChange); } render() { return ( <ul> {this.props.collection.map(model => ( <Item key={model.cid} model={model} /> ))} </ul> ); } }
今日はここまで。