如何在渲染中自动增加索引并打印数组值



我有一个名称数组,我需要循环索引并在呈现中打印名称

const names = ['John','Sara','Michael','Timothy']`
render: (props) => ({
<div>
props=names[];
</div>
});

您将用于。。。在循环中迭代索引。

const names = ['John','Sara','Michael','Timothy'];
for(const index in names) {
console.log(`${index} of ${names[index]}`); 
}

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>

您必须改进代码的这一部分。它看起来不像是JSX的一部分。这里,我认为它可以是:

render() {
const names = ['John','Sara','Michael','Timothy'];
return <div>
{names.map((item, index) => (
<div key={index}>
{item}
</div>
))}
</div>;
}

您可以使用map()来满足您的需求。

render() {
const names = ['John','Sara','Michael','Timothy'];

return (
<div>
{ names.map((name, index) => <div key={index}>{ name }</div> }
</div>
);
}

最新更新