【问题标题】:functions are not valid as a react child, why am I getting this?功能作为反应孩子无效,为什么我会得到这个?
【发布时间】:2018-10-15 08:51:17
【问题描述】:

我遇到了这个问题,我有这个组件

export class MyComponent extends Component {
    myFunc() {

    }

    myFunc2(){

    }
    render this.myFunc() ? (
        <div> 
            { this.myFunc2() ? (
                <AnotherComponent />
            ) : <Fragment />
            }
        </div>
    )
}

但当我尝试在渲染块中渲染 func2 时出现错误:functions are not valid as a react child

但是,当我将它分配给 const 时,例如 const x = this.myFunc2(),然后渲染 x ? something : null。错误消失了

myFuncmyFunc2 都只是根据 props 返回 true 或 false,所以为什么会出现此错误?

为什么我会收到 myFunc2 的错误,而不是 myFunc

【问题讨论】:

  • 从布尔类型的 func2 返回值,以便三元运算符工作。现在你的 func2 正在返回未定义。
  • 认为这与样式化组件有关:/
  • 这是无效的语法。 render 应该是一个方法。
  • 这段代码在语法上无效,不确定你的渲染方法发生了什么

标签: javascript reactjs children react-props


【解决方案1】:

首先,您需要将render 设为类似的函数

render()

其次,你的渲染函数需要返回一个值:

render() { return ....}

最后,你需要完成this.myFunc()条件检查的三元运算符

this.myFunc() ? .... : null

这是一个相同的工作示例:

https://stackblitz.com/edit/react-sdpbgg?file=Hello.js

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 2021-06-20
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    相关资源
    最近更新 更多