React组件可以渲染处于其状态的另一个组件吗?

时间:2019-04-23 11:59:53

标签: reactjs

我试图创建一个容器组件,该组件可能会随着时间的推移而改变其内部组件。

class Container extends React.Component {
    constructor(props) {
        super(props)
        this.state = { content: new FooComponent() }
    }
    render() {
        return <div>
            { this.state.content }
        </div>
    }
}

我收到如下错误:

  

对象作为React子对象无效(找到:带有键{props,context,refs,updater,state}的对象)。如果要渲染子级集合,请改用数组。

我尝试了{ [this.state.component] },但遇到了同样的错误。

您是否可以将this.state中的组件放入render()返回的JSX中?如果没有,如何实现容器?我正在考虑创建一个类似iOS UINavigationController的容器,在其中我可以在堆栈中推送和弹出组件,而仅将顶部的组件呈现到屏幕上。

4 个答案:

答案 0 :(得分:1)

  

React组件可以渲染处于其状态的另一个组件吗?

是的,可以的!

有两种方法

1

import FooComponent from '..'

...
this.state = {
    content: <FooComponent/>
}
...
render(){
    return (
        <div>{this.state.content}</div>
    )
}

2

import FooComponent from '..'

...
this.state = {
    content: FooComponent
}
...
render(){
    const {
        content: BarComponent
    } = this.state

    return (
        <div>
            <BarComponent />
        </div>
    )
}
  

我收到如下错误:

     

对象作为React子对象无效(找到:带有键{props,context,refs,updater,state}的对象)。如果要渲染子级集合,请改用数组。

  • 之所以发生这种情况,是因为当您执行new FooComponent()时它会返回一个对象,而您无法渲染对象。
  • 使用JSX时,将被转换为React.createElement(FooComponent),并且可以渲染。
  • 仅使用FooComponent时,您将存储对它的引用,并且仅在render方法中创建一个将成为React.createElement(BarComponent)的JSX

当组件来自道具时,第二种方法是好的,并且您根据情况希望为其提供一些道具。

工作Example

答案 1 :(得分:1)

您可以使用JSXthis.state = { content: <FooComponent/> }

幕后人物React.createElement()

class Container extends React.Component {
    constructor(props) {
        super(props)
        this.state = { content: <FooComponent/> }
    }
    render() {
        return <div>{this.state.content}</div>;
    }
}

或参考Creating React Elements

这里有一些可读性更高的表格供参考:

class Container extends React.Component {
  state = {
    content: <FooComponent />
  };

  render() {
    return <>{this.state.content}</>;
  }
}
function Container() {
  const [content, setContent] = useState(<FooComponent />);

  return <>{content}</>;
}

答案 2 :(得分:0)

class Container extends React.Component {
 constructor(props) {
    super(props)
    this.state = { content: this.FooComponent() }
  }

 FooComponent(){
  return(<FooComponent/>)
 }

render() {
    return <div>
        { this.state.content }
    </div>
 }
}

答案 3 :(得分:0)

主要问题可能已经回答了there

注意:功能受限-仅存储组件将是简单的无状态视图/屏幕堆栈/缓冲区。

问题可能更加广泛。此解决方案将不等于保存以前的状态,更改...没有道具/参数,没有历史记录,没有上下文,状态反转...但是共享的公共状态(redux存储)可以是一个优势-没有旧状态,无法自动更新整个存储视图链。

相关问题