0
クリックして関数handleDisplayProductをトリガーしてクリックしたオブジェクトに渡したいと思います。これまでは、すべてのオブジェクトに対してリストが生成されたにもかかわらず、関数がhandleイベントを呼び出すと、関数handleDisplayProductが呼び出されました。 それでは、コンテナでイベントonclickをバインドして、それをクリックした要素に渡しますか?Reactの子コンポーネントからオブジェクトをクリックして取得
コンテナ
// Method to retrieve state from Stores
function getAllProductState(){
return {
products: ProductStore.getProducts(),
};
}
export default class ProductAllContainer extends Component {
constructor(props){
super(props);
this.state = getAllProductState();
}
handleDisplayProduct(data){
console.log(data);
// ProductActions.selectProduct(data)
}
render(){
const products = this.state.products;
return(
<div>
{ products.map(function(product,i){
return (
<ProductThumbnail
product = { product }
key = { i }
**onDisplayProduct = { this.handleDisplayProduct(product) }**
/>
)
},this)}
</div>
)
}
}
あなたが反応するクラスにイベントリスナーをバインドする必要があるビュー
const ProductThumbnail = (props)=>{
return(
<div>
<LinksTo to="/" **onClick={props.onDisplayProduct}**>
<h1>{props.product.headline}</h1>
<img src={props.product.images[0].imagesUrls.entry[1].url} alt="Thumbnail small pic"/>
</LinksTo>
</div>
)
}
これに加えて、関数自体の代わりに 'this.handleDisplayProduct'を呼び出した結果を渡すので、' onDisplayProduct = {this.handleDisplayProduct(product)} 'を使用してハンドラを渡すことはできません。代わりに、私は ' 'がここにバインドするのではなく、ハンドラのペイロードを提供することを提案します。 {props.onDisplayProduct(props.product)} ' –
ryanjduffy
@ryanduffy - 代わりに コンポーネントのonClick = {props.onDisplayProduct(props.product)}を追加しました。それがあなたが意味するものならば。アイテムのリストが生成されたにもかかわらず、何もクリックイベントがないときにすべてのオブジェクトを取得しています。デッドフィッシュが提案したバインド(this)を追加しました –
Nicc
@ryanduffy - constハンドラを使ってあなたの提案に従ってください – Nicc