redux 将组件作为属性传递显示错误:未捕获的错误:元素类型无效:应为字符串(对于内置组件)或类/函数

5hcedyr0  于 2022-11-12  发布在  其他
关注(0)|答案(4)|浏览(152)

我有一个名为EditForm的组件,我已将其导入到另一个名为**ProductList的组件中。****我需要将EditForm组件作为道具从ProductList传递到另一个组件ListContainer,并在ListContainer中呈现它(EditForm)。**为了更好地理解,下面给出了流程:

// EditForm.js

const EditForm = () => {...}
export default EditForm

// ProductList.js

import EditForm from "./EditForm"
..
<ListContainer editForm={EditForm} /> // pass the editform as props

// ListContainer.js

const ListContainer({editForm: EditForm}) => {
    ...
    <EditForm /> // use editform here
}

下面是我的代码:

产品列表.js

import React from "react"
import ListContainer from "../common/ListContainer";
import EditForm from "./EditForm";

const ef = () => {
    return (<EditForm />)
}

const ProductList = () => {
    return (
        <React.Fragment>
            <ListContainer  ef={ef} />
        </React.Fragment >
    )
}

export default ProductList

列表容器.js

import React, { useState } from "react"

const ListContainer = ({ ef: EditComponent }) => {
    return (
        <React.Fragment>
                <EditComponent />
        </React.Fragment >
    )
}

export default ListContainer

错误:

完整代码链接:https://onecompiler.com/javascript/3yfvnyyf4

yruzcnhs

yruzcnhs1#

React js已经有了高阶组件概念来处理这些类型的场景,并且返回了新的组件。

rjee0c15

rjee0c152#

虽然最好将子组件作为props.children传递,但如果您已经使用了“export default”,您的代码应该可以正常工作。也许您可以通过调试来检查props,并查找是否有任何拼写错误。

nhjlsmyf

nhjlsmyf3#

如果你想把一个组件传递给孩子来呈现它。正确的React方式是把它作为道具传递。children
例如:

import React from "react"
import ListContainer from "../common/ListContainer";
import EditForm from "./EditForm";

const ProductList = () => {
  return (
    <React.Fragment>
        <ListContainer>
           <EditForm/>
        </ListContainer>
    </React.Fragment >
)
}

export default ProductList

您可以按如下方式访问列表容器中的子项:

import React, { useState } from "react"

const ListContainer = ({ children }) => {
    return (
        <React.Fragment>
                <children />
        </React.Fragment >
    )
}

export default ListContainer

但是,如果你想把它作为你请求的道具传递,那么正确的语法是:

<React.Fragment>
   <ListContainer  ef={EditForm} />
</React.Fragment >

希望这对你有帮助

hpxqektj

hpxqektj4#

最后通过在ListContainer.js中执行以下操作解决了问题

import React from "react"

const ListContainer = (props) => {

// need to use children.types to catch the component in child element

const Edit = props.children.type 

return (
        <React.Fragment>
            <Edit />
        </React.Fragment >
    )
}

export default ListContainer

产品列表.js(与以前相同)

import React from "react"
import ListContainer from "../common/ListContainer";
import EditForm from "./EditForm";

const ProductList = () => {
  return (
    <React.Fragment>
        <ListContainer>
           <EditForm/>
        </ListContainer>
    </React.Fragment >
)
}

export default ProductList

相关问题