React onClick event on component

前端 未结 2 756
长情又很酷
长情又很酷 2020-12-13 22:59

I have a React component called that has many child s (another React component). I want to be able to decl

2条回答
  •  长情又很酷
    2020-12-13 23:50

    Problem

    The problem, as being explained in another answer, is that onClick on a React component (contrary to native DOM element like

    or

    ) is treated as passing of component property, and not of a DOM event handler. And as most likely your component doesn't declare onClick property, that property value simply gets lost.

    Solution

    The most straightforward solution is to add onClick property explicitly on SensorItem component, then pass it to the root DOM element of that component:

    function SensorItem({ prop1, prop2, onClick }) {
      (...)
    
      return (
        

    (...)

    ); }

    But the solution that usually works best for me is to group all the undefined component's properties using object destructuring notation, then pass them all to the root DOM element within that component. This way you can pass onClick, onHover, className etc. without needing to define separate properties for each one of them:

    function SensorItem({ prop1, prop2, ...rootDOMAttributes }) {
      (...)
    
      return (
        

    (...)

    ); }

    No matter which of the two approaches you use, the handler will now work, as it'll now be attached to the root DOM element of SensorItem:

    
    

提交回复
热议问题