在我的实现中,我通过了一个reactelement(至少是我认为的)作为 Prop 。

我想渲染这个 Prop ,因为它是自己的React Component,但是浏览器提示它是一个对象。

要澄清的代码:

在 parent 中:

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元素感到困惑,但是type表示这是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

在 parent 中:

render() {
  return <SortableItem {...extraProps} item={<YourComponent />} />
}

在SortableItem渲染中:
render() {
  return {this.props.item}
}

方法2:
在 parent 中:
render() {
  return <SortableItem {...extraProps} >
     <YourComponent />
  </SortableItem>
}

在SortableItem渲染中:
render() {
  return {this.props.children}
}

关于reactjs - 渲染对象作为React Component,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43584125/

10-09 16:46
查看更多