【问题标题】:React passing component with props and decorate it用 props 反应传递的组件并装饰它
【发布时间】:2021-05-24 17:29:13
【问题描述】:

我有一个反应组件:

<Camera onRecordButton={<Button text="My button Label">}>

在 Camera.js 中,我需要使用我的 Button 组件并附加一些其他道具。 我尝试过使用渲染道具模式和 HOC,但没有收到此错误

Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

在我的 Camera.js 中,我有:

...
{withProps(onRecordButton)}
...

withProps 是:

const Dismiss = ({ children }) => {
    const dismiss = () => {
      console.log('Click')
    }
  
    return children(dismiss)
  }

const withProps = (Component) =>
  (props) => (
    <Dismiss>
      {(dismiss) => (
        <Component onClick={dismiss} {...props} />
      )}
    </Dismiss>
  )

  export default withProps;

我不知道出了什么问题...有什么想法吗?

更新

谢谢sambomartin,但它不起作用,

我正在像这样传递我的组件:

<Camera className="py-5 relative" recordbutton={<Button text="Testo" />} />

这是错误:

react_devtools_backend.js:2560 string (for built-in components) or a class/function (for composite components) but got: <Button />. Did you accidentally export a JSX literal instead of a component?

似乎问题出在 Camera.js 中,并且有一种方法通过 i 传递组件来增强子级:

// Make.js

import Camera from './Camera'
import Button from "../Button/Button";


const Make = () => {

    const {prevStep} = useProgress()

    return (
        <>
      // it work's
      <Camera className="py-5 relative" recordbutton={Button} />

      // NOT  work's
      <Camera className="py-5 relative" recordbutton={<Button text="help!" />} />



            
        </>
    )

}
 
export default Make;

如果我通过不工作,我不明白

这里是一个例子:https://codesandbox.io/s/react-hoc-ksjbf

【问题讨论】:

    标签: reactjs components


    【解决方案1】:

    您需要正确构造/破坏道具。在您的示例中,您传递的函数是道具。

    const Dismiss = ({ children }) => {
    const dismiss = () => {
      console.log('Click')
    }
    
    return children( {dismiss} )
    }
    
    const withProps = (Component) =>
      (props) => (
        <Dismiss>
          {({dismiss}) => (
            <Component onClick={dismiss} {...props} />
          )}
        </Dismiss>
      )
    
      export default withProps;
    

    【讨论】:

    • Thx sambomartin 但它不起作用,请检查我的答案更新;)
    猜你喜欢
    • 1970-01-01
    • 2021-03-01
    • 2019-06-11
    • 2021-12-28
    • 2020-09-08
    • 2020-10-07
    • 1970-01-01
    • 2021-01-24
    • 2023-04-02
    相关资源
    最近更新 更多