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>
)
}
)
}
此 .map() 方法未按预期工作。
通过代码,我试图获得
hello [button]
myNameIs [button]
像这样。
但是当我实际渲染代码时,我得到
hello MynameIs [button]
遇到这种情况,如何修改.map()语句?
我应该使用索引吗?
在 div
标签内创建按钮。您也可以根据需要使用样式来对齐项目
array.map((arr) => (
<div>{arr} <button>Edit</button></div>
)
看看下面的例子,我几乎是用你的代码创建的,它按你预期的方式工作,没有问题。
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>
const test = () = {
const array = ['hello', 'myNameIs']
return (
{array.map((item,key) => (
<div key={item}>{item}</div><button>Edit</button>
)})
}
您没有使用正确的箭头函数语法
它应该像
const test = ()=>{}
React 组件 JSX 应该 return 一个父容器尝试像这样包装它:
const Test = () => {
const array = ["hello", "myNameIs"];
return (
<>
{array.map((arr) => {
return (
<>
<div>{arr}</div>
<button>Edit</button>
</>
);
})}
</>
)
}
这是工作代码沙箱 link https://codesandbox.io/s/kind-easley-jxiei?file=/src/App.js:57-336
希望对您有所帮助。
const test = () = {
const array = ['hello', 'myNameIs']
return (
{
array.map((arr) => (
<div>{arr}</div>
<button>Edit</button>
)
}
)
}
此 .map() 方法未按预期工作。
通过代码,我试图获得
hello [button]
myNameIs [button]
像这样。
但是当我实际渲染代码时,我得到
hello MynameIs [button]
遇到这种情况,如何修改.map()语句?
我应该使用索引吗?
在 div
标签内创建按钮。您也可以根据需要使用样式来对齐项目
array.map((arr) => (
<div>{arr} <button>Edit</button></div>
)
看看下面的例子,我几乎是用你的代码创建的,它按你预期的方式工作,没有问题。
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>
const test = () = {
const array = ['hello', 'myNameIs']
return (
{array.map((item,key) => (
<div key={item}>{item}</div><button>Edit</button>
)})
}
您没有使用正确的箭头函数语法
它应该像
const test = ()=>{}
React 组件 JSX 应该 return 一个父容器尝试像这样包装它:
const Test = () => {
const array = ["hello", "myNameIs"];
return (
<>
{array.map((arr) => {
return (
<>
<div>{arr}</div>
<button>Edit</button>
</>
);
})}
</>
)
}
这是工作代码沙箱 link https://codesandbox.io/s/kind-easley-jxiei?file=/src/App.js:57-336
希望对您有所帮助。