简体   繁体   中英

Can't pass children with props using React.cloneElement?

I got this error

invariant.js:42 Uncaught Error: Element type is invalid

doing this

const ListWrap = ({ children, onChange }) => {
  return <div>{React.cloneElement(children, { onChange })}</div>
}

But no issue when I do

const ListWrap = ({ children }) => {
  return <div>{children}</div>
}

But I can't pass the props by merely doing return <div>{children}</div> . Any clue what went wrong?

React.cloneElement takes a single child. This should fix it:

const ListWrap = ({ children, onChange }) => {
  return (
    <div>
    {React.Children.map(children, child => React.cloneElement(child, { onChange }))}
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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