简体   繁体   English

React props id 绑定到无状态组件中的 onClick

[英]React props id binding to onClick in a stateless component

I have a class based component that is passing props down我有一个基于类的组件,它正在传递道具

onClickHandler = () => {doSomething};

return (
   <Container 
    jobs={this.props.jobs}
    clicked={this.onClickHandler}
   />
);

...to a stateless component: ...到无状态组件:

const Container = props => {

 return (
  <div>
   {props.jobs.map(job => 
     <p onClick={props.clicked} key={job.id}>
        {job.title}
     </p>
    )}
   </div>
 );
}

Is there a way to pass on the key/id via the clicked prop - back up to the onClickHandler?有没有办法通过 clicked prop 传递键/id - 备份到 onClickHandler?

I have looked at other similar questions on here and have tried to use bind to add the key to the clicked prop but am having real trouble passing the key on to the onClickHandler.我在这里查看了其他类似的问题,并尝试使用绑定将键添加到被点击的道具,但在将键传递给 onClickHandler 时遇到了真正的麻烦。 Thank you for any advice!感谢您的任何建议!

How about passing a function to onClick .将函数传递给onClick怎么样。

You can the pass along arguments to props.clicked() .您可以将参数传递给props.clicked()

How about this:这个怎么样:

const Container = props => {
  return (
    <div>
      {props.jobs.map(job => 
        <p onClick={() => props.clicked(job.id)} key={job.id}>
          {job.title}
        </p>
      )}
    </div>
  )
}

Yeah, with the clickHandler function, you get an event object in the argument:是的,使用 clickHandler 函数,您会在参数中获得一个事件对象:

onClickHandler = (event) => {// use the event obj to get key/id };

You can use that event object to find the key/id of any element inside the target element you clicked.您可以使用该事件对象来查找您单击的目标元素内的任何元素的键/ID。

You can use bind to pass the arguments list back to the listener.您可以使用bind将参数列表传递回侦听器。

<p onClick={ props.clicked.bind(null, job.id) } key={job.id}>

And first argument when the event is invoked has the id调用事件时的第一个参数具有id

onClickHandler = (id) => {
   doSomething(id);
};

return (
   <Container jobs={this.props.jobs} clicked={this.onClickHandler} />
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM