javascript - 如何在另一个组件的渲染方法中渲染存储在数组中的 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;
解决方案
解决此问题的正确方法是在您的渲染方法中:
{ this.searchResultsComponents.map((it, index) => <it key={index} />) }
该键是可选的,但在渲染组件数组时,react 建议使用它来提高渲染性能。
有关更多详细信息,请参阅https://reactjs.org/docs/lists-and-keys.html#basic-list-component。
您的方法不起作用,因为只需调用 render 方法,函数调用就会返回 HTML DOM。但是,您只是调用该函数而不对返回值做任何事情。
推荐阅读
- filter - 带有 uuid 的 API 平台过滤器
- hadoop - HIVE如何根据某些条件更新现有数据,如果不存在则插入新数据
- r - 将 Rstudio 与 Docker 组合一起使用并将环境变量传递给 rstudio 用户
- python - 将 json 数据发布到模型时,Django Not null 约束失败
- html - 表结构的对齐问题
- java - 返回两个数字的索引,使它们加起来为特定目标
- javascript - 如何使用 javascript 左右对齐 HTML DATA
- html - 在引导程序 4 的导航栏中悬停时未显示箭头
- css - 为什么我的菜单项在小屏幕上重叠?
- reactjs - Jest 如何测试反应表单提交?