为什么我收到警告:函数作为 React 子级无效?

新手上路,请多包涵

当我尝试调用返回 map 方法结果的方法时,我收到以下错误 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render 但我不知道为什么。这是我的代码:

 renderAlbums() {
        return this.state.albums.map(album => <Text>{ album.title }</Text>);
    }

    render() {
        return (
            <View>
                { this.renderAlbums }
            </View>
        );
    }

但是我上面的代码我看不出问题出在哪里。但是当我尝试在我的 render() 方法中创建一个变量时,通过我的 map() 方法,一切正常:

 render() {
  const c=this.state.albums.map(album => <Text>{ album.title }</Text>);
    return (
        <View>
            { c }
        </View>
    );
}

我想了解为什么它不起作用。当我在这里调用渲染 renderAlbums() 方法时 <View>{ this.renderAlbums }</View>

而且对我来说似乎更奇怪的是,当我尝试像这样调用 renderAlbums() <View>{ this.renderAlbums() }</View> 时,它可以使用括号。

原文由 Christian Lisangola 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 418
2 个回答

警告:函数作为 React 子级无效。如果您返回 Component 而不是从渲染中返回,则可能会发生这种情况

基本上,React 期望 React Elements 来渲染它。

在当前脚本中, this.renderAlbums 是一个 函数引用,它不返回任何 React Element 。函数本身没有反应元素。所以,反应无法渲染 this.renderAlbums

 <View>
   { this.renderAlbums }
</View>

正确方法:

 <View>
   { this.renderAlbums() } //it will return react element which can be rendered.
</View>

原文由 RIYAJ KHAN 发布,翻译遵循 CC BY-SA 4.0 许可协议

this.renderAlbums 指的是实际函数本身,而 this.renderAlbums() 实际执行函数,因此代表函数的返回值。

原文由 Jayce444 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题