从React中的子组件中单击该对象

时间:2016-08-09 16:17:00

标签: reactjs flux

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

容器

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

1 个答案:

答案 0 :(得分:1)

您需要将事件侦听器绑定到react类。你可以这样做。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>

typedef struct proxy_node_t{
    pthread_t sub_thread;
    pthread_t p_self;
}proxy_node;

proxy_node* proxy;

static void proxy_singnal_handler(int sig){
    write(1, "Hello\n", 6);
    return;
}

static void* t_consensus(void *arg){
    signal(SIGINT,proxy_singnal_handler);
    while(1); /* infinite loop */
    return NULL;
}

int main(int argc, char **argv)
{
    proxy = (proxy_node*)malloc(sizeof(proxy_node));
    proxy->p_self = pthread_self();
    pthread_create(&proxy->sub_thread,NULL,t_consensus,NULL);
    sleep(2); /* delay to ensure signal handler is installed */
    pthread_kill(proxy->sub_thread,SIGINT);
    sleep(2); /* delay to ensure signal gets executed before the process exits */
    return 0;
}

或者使用es6,您可以使用箭头功能。

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

注意:类属性还不是当前JavaScript标准的一部分。因此,除非您添加handleDisplayProduct = (data) => { console.log(data); // ProductActions.selectProduct(data) } babel插件

,否则第二个示例将无效

编辑:@ryanjduffy还指出了代码中的一个重要错误。请参阅他的评论。

相关问题