React中获取子组件点击的对象

Get the object clicked from the child component in React

我想在单击时触发函数 handleDisplayProduct 并将单击的对象传递给它。到目前为止,它会在为所有对象生成列表时调用函数 handleDisplayProduct,但不会在单击事件上触发该函数。 那么我如何将事件 onclick 与容器绑定并将单击的元素传递给它?

容器

// 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>
 )
}

您需要将事件侦听器绑定到反应 class。你可以这样做。

constructor(props){
  super(props);
  this.state = getAllProductState();
  this.handleDisplayProduct = this.handleDisplayProduct.bind(this);
}

或者使用 es6,您可以改用箭头函数。

handleDisplayProduct = (data) => {
 console.log(data);
 // ProductActions.selectProduct(data)
}

注意:Class 属性还不是当前 JavaScript 标准的一部分。所以第二个例子不会工作,除非你添加一个 babel-plugin-transform-class-properties babel 插件

编辑:@ryanjduffy 还指出了您代码中的一个严重错误。参考他的评论。