【问题标题】:React Native: Conditionally Render ComponentsReact Native:有条件地渲染组件
【发布时间】:2018-12-20 05:32:38
【问题描述】:

我搜索了这个问题,找到了一个解决方案,它说根据状态有条件地渲染如下:

  render() {

    const content = this.state.isReady ? <Home/> : <Splash/>;

    return (
      {content}
    );
  }

但是,我不断收到Invariant Violation: Objects are not valid a React child (found object with keys {content}.

【问题讨论】:

  • return content;

标签: react-native


【解决方案1】:

使用简单的 if else 代替三元表达式,因为有时三元运算符会“返回”内部的任何内容并且无法执行代码块。

if (this.state.isReady) {
    return <Home />
} else {
    return <Splash />
}

【讨论】:

    【解决方案2】:

    您的输入错误,您返回了Object,而是在 JSX 元素之间使用:

    const Ready = () => <div>Ready</div>
    const NotReady = () => <div>NotReady</div>
    
    class App extends Component {
      constructor() {
        super();
        this.state = {
          isReady: false
        };
      }
    
      render() {
        const content=this.state.isReady ? <Ready /> : <NotReady />
        return (
          <div>
            {content}
          </div>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多