在我的实现中,我传递了一个reactelement(至少我是这么认为的)作为 Prop 。
我想将这个 prop 渲染为它自己的 React 组件,但浏览器提示它是一个对象。
澄清代码:
在父级中:
render() {
return <SortableItem {...extraProps} item={React.cloneElement(item, extraProps)} />
}
item
prop 包含我想要在 SortableItem
中渲染的元素
在 SortableItem 渲染中:
我想做这样的事情:
render() {
return <props.item />
}
当我登录时props.item
我明白了:
Object {$$typeof: Symbol(react.element), key: "item-5", ref: null, props:
Object, type: function…}
$$typeof:Symbol(react.element)
key:"item-5"
props:Object
ref:null
type:function _class()
我很困惑为什么$$typeof
会说这确实是一个 react 元素,但类型说它是一个 function _class()
当我记录/渲染时,浏览器说它是一个对象。
这是我在渲染时在浏览器中遇到的错误 <props.item />
在SortableItem
Fatal Exception:Uncaught Invariant Violation: Element type is invalid:
expected a string (for built-in components) or a class/function (for
composite components) but got: object. Check the render method of
`SortableItem`.(reload cancelled)
最佳答案
试试这个,
方法 1
在父级中:
render() {
return <SortableItem {...extraProps} item={<YourComponent />} />
}
在 SortableItem 渲染中:
render() {
return {this.props.item}
}
方法 2: 在父级中:
render() {
return <SortableItem {...extraProps} >
<YourComponent />
</SortableItem>
}
在 SortableItem 渲染中:
render() {
return {this.props.children}
}
关于reactjs - 将对象渲染为 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43584125/