4 回答

TA貢獻1851條經驗 獲得超4個贊
您可以使用for ... in循環來迭代索引。
const names = ['John','Sara','Michael','Timothy'];
for(const index in names) {
console.log(`${index} of ${names[index]}`);
}

TA貢獻1995條經驗 獲得超2個贊
const names = ["John", "Sara", "Michael", "Timothy"];
class Content extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<h1>Names</h1>
{this.props.names ? (
this.props.names.map((name, index) => (
<p key={name + index}>{name}</p>
))
) : (
<p>No names found</p>
)}
</div>
);
}
}
ReactDOM.render(<Content names={names} />, document.getElementById("app"));
<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="app"> </div>

TA貢獻1887條經驗 獲得超5個贊
您可以使用它map()來完成您的需求。
render() {
const names = ['John','Sara','Michael','Timothy'];
return (
<div>
{ names.map((name, index) => <div key={index}>{ name }</div> }
</div>
);
}

TA貢獻2041條經驗 獲得超4個贊
您必須改進代碼的一部分。它看起來不像是 JSX 部分。在這里,我想它可以是:
render() {
const names = ['John','Sara','Michael','Timothy'];
return <div>
{names.map((item, index) => (
<div key={index}>
{item}
</div>
))}
</div>;
}
添加回答
舉報