为什么我收到警告:函数作为 React 子节点无效? [英] Why am I getting Warning: Functions are not valid as a React child?
问题描述
当我尝试调用返回 map 方法结果的方法时,出现以下错误 警告:函数作为 React 子节点无效.如果您返回 Component 而不是 <Component/> ,则可能会发生这种情况.来自渲染
但我不知道为什么.这是我的代码:
When I try to call a method which returns the result of the map method, I get the following error Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render
but I don't know why. Here is my code:
renderAlbums() {
return this.state.albums.map(album => <Text>{ album.title }</Text>);
}
render() {
return (
<View>
{ this.renderAlbums }
</View>
);
}
但是我上面的代码我没有看到问题出在哪里.但是当我尝试在我的 render()
方法中创建一个变量时,在其中传递我的 map()
方法,一切正常:
But I the code above I don't see where the problem comes from. But when I try to create a variable in my render()
method in which a pass my map()
method,everything works good:
render() {
const c=this.state.albums.map(album => <Text>{ album.title }</Text>);
return (
<View>
{ c }
</View>
);
}
我想了解为什么它不起作用.当我在这里调用渲染 renderAlbums()
方法时
.
I would like to understand why it doesn't work. When I call the render renderAlbums()
method here <View>{ this.renderAlbums }</View>
.
而且对我来说更奇怪的是,当我尝试像这样调用 renderAlbums()
时 <View>{ this.renderAlbums() }</View>
带括号它有效.
And And what seems even weirder to me is that when I try to call the renderAlbums()
like this <View>{ this.renderAlbums() }</View>
with parentheses it works.
推荐答案
警告:函数作为 React 子节点无效.如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render
基本上,React 期望 React Elements
呈现
Basically,React expecting the React Elements
to render it.
在当前脚本中,this.renderAlbums
是一个函数引用,它不返回任何React Element
.Function 本身不是反应元素.所以,React 无法渲染 this.renderAlbums
.
In current script,this.renderAlbums
is a function reference which not returning any React Element
.Function itself not react element.So,React unable to render the this.renderAlbums
.
<View>
{ this.renderAlbums }
</View>
正确方法:
<View>
{ this.renderAlbums() } //it will return react element which can be rendered.
</View>
这篇关于为什么我收到警告:函数作为 React 子节点无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!