当我试图调用一个返回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>
        );
    }

但我不明白上面的代码是从哪里来的.但当我try 在我的render()方法中创建一个变量,其中一个通过我的map()方法时,一切都很好:

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

我想知道为什么它不起作用.当我在这里调用render renderAlbums()方法<View>{ this.renderAlbums }</View>时.

对我来说更奇怪的是,当我试着用括号来称呼renderAlbums(),比如<View>{ this.renderAlbums() }</View>时,它是有效的.

推荐答案

警告:函数作为子函数无效.如果返回的是组件而不是渲染,则可能会发生这种情况

基本上,react 是期望React Elements来呈现它.

在当前脚本中,this.renderAlbums是一个function reference,不返回任何React Element.功能本身不react 元素.因此,React无法渲染this.renderAlbums.

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

correct way:

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

React-native相关问答推荐

React Navigation—从标题按钮打开模式

React Native:任务 ':app:checkDebugDuplicateClasses' 执行失败

Javascript setTimeout 立即在 React Native 中运行

React Native WebView onMessage 没有做任何事情

React-native -run-ios 错误无法构建 iOS 元素.我们运行了xcodebuild命令,但它以错误代码 65 退出

如何从 Firebase 获取所有设备令牌?

更改整个 React Native App 的语言

由于依赖关系,在 run-android 上构建失败

react Navigation 在标题中使用图像?

如何在 React Native 中获取 TextInput 相对于其父级或屏幕的光标位置

如何从 React Native-App 中的 res/drawable-folder 加载图像?

SyntaxError: const 声明中缺少初始化程序

如何在 React Native 中按住以 Select 文本

如何在不使用 JSX 的情况下在 React Native 中制作组件?

opneUrl react-native 链接调用,mailto

如何在react-native矢量图标中从多个文件导入图标?

ENOENT: no such file or directory, 打开 'android/app/src/main/assets/index.android.bundle'

在 webview 中检测touch 是 Apple Pencil 还是手指(react-native)

ListView 和 FlatList 有什么区别?

尽管 TypeScript 编译器错误,为什么我的 React Native 应用程序构建成功?