首页 > 解决方案 > 如何在另一个组件的渲染方法中渲染存储在数组中的 React 组件

问题描述

我有一个组件,我们调用Screen,它会导入一个包含搜索结果的组件。Screen 中的一个方法循环遍历一个对象数组,并为每个对象实例化一个新的搜索结果组件并将它们存储在一个数组中。

我是 React 的新手,所以我的问题是,使用new关键字创建扩展 Component 的类的实例是否正确,或者是否有适当的 React 方法来做到这一点?如果是这样,那么在 Screen 类中呈现这些组件的正确方法是什么,因为我在下面的代码段中执行此操作的方式似乎不起作用,因为没有呈现任何内容。

Screen.js - 我已经削减了文件以显示我在说什么

import React, { Component } from "react";
import { Text, View } from "react-native";

import SearchResult from "components/SearchResult";


class Screen extends Component {
    searchResultsComponents = [];

    submitSearchQuery(searchParam /* Array of objects */) {
        this.searchResultsComponents = [];
        for(let result in this.searchResults) {
            this.searchResultsComponents.push(new SearchResult(this.searchResults[result]));
            }
            this.forceUpdate();
        });
    }

    render() {
        return(
            <View>  
                { this.searchResultsComponents.forEach((it) => { it.render(); }) }
            </View>
        );
    }
}

export default Screen;

搜索结果.js

import React, { Component } from "react";
import { Text, View } from "react-native";


class SearchResult extends Component {
    title;
    setTitle(title) {
        this.title = title;
    }
    getTitle() {
        return this.title;
    }

    description;
    setDescription(description) {
        this.description = description;
    }
    getDescription() {
        return this.description;
    }

    constructor(searchResult) {
        super();
        this.setTitle(searchResult.snippet.title);
        this.setDescription(searchResult.snippet.description)
    }

    render() {
        return(
            <View>
                <Text>{ this.title }</Text>
                <Text>{ this.description }</Text>
            </View>
        );
    }
}

export default SearchResult;

标签: javascriptreactjsreact-native

解决方案


解决此问题的正确方法是在您的渲染方法中:

 { this.searchResultsComponents.map((it, index) => <it key={index} />) }

该键是可选的,但在渲染组件数组时,react 建议使用它来提高渲染性能。

有关更多详细信息,请参阅https://reactjs.org/docs/lists-and-keys.html#basic-list-component

您的方法不起作用,因为只需调用 render 方法,函数调用就会返回 HTML DOM。但是,您只是调用该函数而不对返回值做任何事情。


推荐阅读