简体   繁体   English

array.map() 在 React JS 中一起返回元素

[英]array.map() is returning elements all together in React JS


const test = () = {

const array = ['hello', 'myNameIs']

return (

{
array.map((arr) => (
  <div>{arr}</div>
  <button>Edit</button>
  )
}

)

}

This.map() method is not working as I intended. This.map() 方法没有按我的预期工作。

With the code, I was trying to get使用代码,我试图得到

hello [button]
myNameIs [button]

like this.像这样。

But when I actually render the code, I get但是当我实际渲染代码时,我得到了

hello MynameIs [button]

In this kind of situation, How can I change the.map() statement?在这种情况下,如何更改 .map() 语句?

Should I use an index?我应该使用索引吗?

Take a look at below example, I created it almost by your code, it is working as you expected without problem.看看下面的例子,我几乎是用你的代码创建的,它按照你的预期工作,没有问题。

 function App() { const array = ['hello', 'myNameIs']; return array.map(item => ( <div key={item}> {item} <button>Edit</button> </div> )); } ReactDOM.render(<App />, document.getElementById("root"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

Create the button inside the div tagdiv标签内创建按钮

array.map((arr) => (
  <div>{arr} <button>Edit</button></div>
 )
const test = () = {
  const array = ['hello', 'myNameIs']
  return (

  {array.map((item,key) => (
    <div key={item}>{item}</div><button>Edit</button>
  )})
}

You are not using the correct syntax for the arrow function It should be like const test = ()=>{} React component JSX should return one parent container try wrapping it like:您没有使用正确的箭头 function 语法它应该像const test = ()=>{} React 组件 JSX 应该返回一个父容器尝试将其包装为:

 const Test = () => { const array = ["hello", "myNameIs"]; return ( <> {array.map((arr) => { return ( <> <div>{arr}</div> <button>Edit</button> </> ); })} </> ) }

Here is the working code sandbox link https://codesandbox.io/s/kind-easley-jxiei?file=/src/App.js:57-336这是工作代码沙箱链接https://codesandbox.io/s/kind-easley-jxiei?file=/src/App.js:57-336

I Hope it helps.我希望它有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM