#reactjs
Вопрос:
Я создал функцию карты, которая должна отображать массив и отображать элементы массива, но по какой-то причине она не работает.
Вот файл с массивом:
const AboutContents = [
{
id: 1,
image: "",
title: "Feature 1",
description: "Description goes here"
},
{
id: 2,
image: "",
title: "Feature2",
description:"Description goes here"
},
{
id: 3,
image: "",
title: "Feature 3",
description: "Description goes here"
}
];
export default AboutContents;
А вот файл с записью:
import React from "react";
import AboutContent from "./AboutContent"; //Probably unnecessary
function Entry(props) {
return (
<div>
<img src={props.image} alt="" width="500" height="600"></img>
<h3>{props.title}</h3>
<p>{props.description}</p>
</div>
);
}
export default Entry;
А вот файл About.jsx. Здесь находится функция map Примечание: я также использую react-bootstrap, но я не думаю, что это будет проблемой:
import React from "react";
import Entry from "./Entry";
import AboutContents from "./AboutContent";
import { Container, Row, Col } from "react-bootstrap";
function About(props) {
return (
<div>
<h1 class="aboutText">About</h1>
<Container fluid>
<div class="row">
{AboutContents.map(aboutItem => {
return(
<div class='col-lg-4 col-md-4'>
<Entry
key={AboutContents.id}
image={AboutContents.image}
title={AboutContents.title}
description={AboutContents.description}
/>
</div>
)
})}
</div>
</Container>
</div>
);
}
export default About;
Ответ №1:
Похоже, вы пытались использовать сам AboutContents
массив, а aboutItem
не внутри функции карты.
Попробуйте вместо этого переключиться на это.
{AboutContents.map(aboutItem => {
return(
<div class='col-lg-4 col-md-4'>
<Entry
key={aboutItem.id}
image={aboutItem.image}
title={aboutItem.title}
description={aboutItem.description}
/>
</div>
)
})}
Ответ №2:
Пожалуйста, проверьте приведенный ниже пример:-
const AboutContents = [
{
id: 1,
image: "",
title: "Feature 1",
description: "Description goes here"
},
{
id: 2,
image: "",
title: "Feature2",
description: "Description goes here"
},
{
id: 3,
image: "",
title: "Feature 3",
description: "Description goes here"
}
];
const Entry = (props) => {
return (
<div>
<img src={props.image} alt="" width="500" height="600" />
<h3>{props.title}</h3>
<p>{props.description}</p>
</div>
);
}
const App = () => {
return AboutContents.map((item, index) => (
<Entry key={index} {...item}/>
));
}
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>