当我尝试调用返回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()
处调用render <View>{ this.renderAlbums }</View>
方法时为什么它不起作用。
对我来说,甚至更奇怪的是,当我尝试用括号将这样的renderAlbums()
称为<View>{ this.renderAlbums() }</View>
时,它起作用了。所以我真的很困惑
答案 0 :(得分:4)
this.renderAlbums
指的是实际的函数本身,而this.renderAlbums()
实际执行该函数,因此代表该函数的返回值。
答案 1 :(得分:4)
警告:函数作为React子元素无效。如果您返回一个Component而不是从render返回,则可能会发生这种情况
基本上,请期待React Elements
进行渲染。
在当前脚本中,this.renderAlbums
是一个函数引用,它不会返回任何React Element
。函数本身没有对元素的反应。因此,React无法呈现{{1} }。
this.renderAlbums
正确的方法:
<View>
{ this.renderAlbums }
</View>