我有一个名称数组,我需要遍历索引并在render中打印名称
const names = ['John','Sara','Michael','Timothy']`
render: (props) => ({
<div>
props=names[];
</div>
});
答案 0 :(得分:2)
您可以在循环中使用 for ... 来遍历索引。
const names = ['John','Sara','Michael','Timothy'];
for(const index in names) {
console.log(`${index} of ${names[index]}`);
}
答案 1 :(得分:1)
您可以使用map()
来满足您的需求。
render() {
const names = ['John','Sara','Michael','Timothy'];
return (
<div>
{ names.map((name, index) => <div key={index}>{ name }</div> }
</div>
);
}
答案 2 :(得分:1)
您必须改进代码部分。它似乎不像JSX的一部分。在这里,我想应该是这样的:
render() {
const names = ['John','Sara','Michael','Timothy'];
return <div>
{names.map((item, index) => (
<div key={index}>
{item}
</div>
))}
</div>;
}
答案 3 :(得分:1)
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>