score:19

Accepted answer

there isn't any good way of doing this. you can use something like this. but, if you pass more than one child here, all of them will respond to this click handler! so, you should think of another logic to use this button. as in this state, your childrencomponent is so generic.

so, what will your button component do? you can create a component with this click handler and all other parts can be passed as props. maybe in this way you can use it in multiple places.

const app = () => (
  <div>
    <childcomponent>
      <button>click</button>
    </childcomponent>
  </div>
);

const childcomponent = ( props ) => {
  const handleclick = () => console.log( "clicked" );
  return (
    <div>
      { react.cloneelement( props.children, { onclick: handleclick } ) }
    </div>
  );
};

reactdom.render(
  <app />,
  document.getelementbyid("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

score:0

function child(props, ref) {
    useimperativehandle(ref, () => ({
        onclick: () => {
            //do something
        }
    }));
    return <div>child</div>;
}

child = forwardref(child);


function parent(props) {
    childref = useref()
    //here you can call it fom parent 
    childref.current.focus()
    return (
        <child ref={childref} />
    )
}

Related Query

More Query from same tag