これは私が達成しようとしているものです。私はProductList
の成分の中に示されている2つの反応成分Product
とProductInfoPanel
を持っています。 Product
には、製品名や価格などの製品に関する選択情報が表示されます。製品をクリックすると、詳細がProductInfoPanel
に表示されます。だから私はProductInfoPanel
にクリックしたワウの羽を渡す必要があります。React:状態を使わずにレンダリングメソッドの外からコンポーネントの小道具を更新する
ここでは、どのようにそれらを一緒に接続しています。各Product
は、クリックハンドラを受け取り、呼び出されたときにproduct
オブジェクトを戻し、それはProductInfoPanel
の小道具に渡されます。 ProductList
は、何がクリックされたかを追跡するために状態を使用するため、変更すると情報パネルの再レンダリングがトリガーされます。
class ProductList extends React.Component {
render() {
return (
<div>
<div className='content'>
<ul>
{ this.props.products.map((product, index) => {
return (
<li key={index}>
<Product product={product}
clickHandler={this.onProductClicked.bind(this)}/>
</li>
);
})}
</ul>
</div>
<div className='side-panel'>
<ProductInfoPanel product={this.state.selectedProduct} />
</div>
</div>
);
}
onProductClicked(clickedProduct) {
// Use the product object that was clicked, and updates the state.
// This updates the info panel content.
this.setState({ selectedProduct: clickedProduct });
}
}
ここでは、2つのコンポーネントがどのように構築されるかについて説明します。
class Product extends React.Component {
render() {
// Even though it needs only name and price, it gets the whole product
// object passed in so that it can pass it to the info panel in the
// click handler.
return (
<div onClick={this.onClicked.bind(this)}>
<span>{this.props.product.name}</span>
<span>{this.props.product.price}</span>
</div>
);
}
onClicked(e) {
this.props.clickHandler(this.props.product);
}
}
class ProductInfoPanel extends React.Component {
render() {
// Info panel displays more information about a product.
return (
<ul>
<li>{this.props.product.name}</li>
<li>{this.props.product.price}</li>
<li>{this.props.product.description}</li>
<li>{this.props.product.rating}</li>
<li>{this.props.product.review}</li>
</ul>
);
}
}
これは私が思いつくことができる最高ですが、どの製品がクリックされたのかを把握するために状態を使用しても間違っています。つまり、実際にコンポーネントの状態ではありませんか?
私は、参照のprops
を更新することができる場合は、私は各Product
からProductInfoPanel
への参照を渡すためにしようと思い、render
方法の外からコンポーネントを反応するので、彼らは彼らのクリックハンドラでそれを更新し行うことができます。
私が望むものを達成し、クリックしたものを追跡するために状態を使用しないようにする方法はありますか?