You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无JSX与Redux的React环境下,如何将数组转为列表元素?

Solution: Create a List in React Without JSX or Redux

Hey there! The issue you're hitting is that when you pass an array of strings directly to React.createElement, React automatically wraps each string in a <span> tag. To get proper list items (<li>), you need to explicitly create each list element using React.createElement for every item in your array.

Here's how to do it correctly:

We’ll use Array.map() to iterate over your arrr array and generate an array of <li> elements. Then we’ll wrap those in a <ul> (unordered list) and finally nest that list inside your container <div>.

Working Code Example:

var arrr = ['foodA', 'foodB', 'foodC'];

// Generate individual list items with unique keys
const listItems = arrr.map((food, index) => 
  React.createElement('li', { key: index }, food)
);

// Build the container div with the nested list
const answer = React.createElement(
  'div', 
  null, 
  React.createElement('ul', null, listItems)
);

// Render to your DOM root (adjust the ID to match your page)
ReactDOM.render(answer, document.getElementById('root'));

Key Details to Know:

  • Why map() instead of forEach()?: map() returns a new array of the <li> elements that React can directly render. forEach() only iterates through the array and doesn’t return anything, so it won’t produce the elements we need.
  • The key prop: Adding a unique key to each list item helps React efficiently update the list later. We’re using the array index here for simplicity, but if your data had unique identifiers (like IDs), those would be better to use.
  • Nested createElement calls: We nest the <ul> inside the container <div>, and pass our array of <li> elements as children to the <ul>—this is how you build nested structures without JSX.

This will render exactly what you want: a div containing an unordered list with foodA, foodB, foodC as proper list items, no unwanted spans!

内容的提问来源于stack exchange,提问作者bird

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:37:23