我正在尝试根据这样的 JSON 对象列表动态地创建一些元素:
{Object.entries(this.state.topTen).forEach(([name]) => {
console.log(name); // this correctly print the list of names
React.createElement(MyCustomComponent, {name: name});
})}
我还在循环中尝试了以下方法:
<MyCustomComponentname={name} />
但是我在屏幕上看不到任何呈现的内容,我确信它this.state.topTen
具有正确的信息,因为console.log
循环内部正在显示正确的信息。如果我<MyCustomComponentname={name} />
在循环之外添加一个,组件就会正确呈现。
该方法.forEach()
不会返回任何内容。您将需要使用.map()
数组的方法并返回React.createElement(MyCustomComponent, {name: name});
.
例如:
{Object.entries(this.state.topTen).map(([name]) => {
console.log(name); // this correctly print the list of names
return React.createElement(MyCustomComponent, {name: name});
})}
Using.map()
将返回一个数组,其中包含您在回调中返回的任何项目。这个结果数组可以用 React 渲染,因为回调返回React.createElement(...)
.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句