所以我知道如何使用map从状态渲染数组 在这里,我有一个组件状态的两个数组。我想用内部图像渲染每个链接。第一个图像应该在第一个链接等内。
我如何用React来完成这个?
<a href={}>
<img src={} />
</a>
this.state = {
links: [
'https://www.google.com',
'https://www.youtube.com',
'https://twitter.com/'
],
images: [
'https://static.pexels.com/photos/380863/pexels-photo-380863.jpeg',
'https://static.pexels.com/photos/350772/pexels-photo-350772.jpeg',
'https://static.pexels.com/photos/289506/pexels-photo-289506.jpeg'
]
}
答案 0 :(得分:2)
你可以这样做:
render() {
const { links, images } = this.state;
return links.map((href, i) => (
<a href={href}>
<img src={images[i]} />
</a>
));
}
确保您拥有相同数量的链接和图片,否则如果您拥有的链接多于图片,则会出现问题。 我不知道你的其余代码是什么,但将数据结构更改为这样可能是有意义的:
const links = [
{
href: 'https://www.google.com',
src: 'https://static.pexels.com/photos/380863/pexels-photo-380863.jpeg'
},
...
];
此外,如果该组件角色仅用于显示链接,则应该使其无状态:
function Link({ href, src }) {
return (
<a href={href}>
<img src={src} />
</a>
);
}
function Links({ links }) {
return links.map(link => <Link {...link} />);
}
答案 1 :(得分:0)
你可以在你的状态下创建一个对象,其中对象的键是链接,值是图像链接,然后像这样使用它:
{Object
.keys(this.props.links)
.map(renderLink)}
现在你需要在组件中使用renderLink函数:
renderLink(key) {
const image = this.props.links[key];
return (
<a href={key}>
<img src={image} />
</a>
);
}
您还需要记住将此方法绑定到组件
constructor() {
super();
this.renderLink = this.renderLink.bind(this);
}
答案 2 :(得分:0)
我认为更简洁的方法是与zipObject库中的Lodash功能相同。
const links = [
'https://www.google.com',
'https://www.youtube.com',
'https://twitter.com/'
];
const images = [
'https://static.pexels.com/photos/380863/pexels-photo-380863.jpeg',
'https://static.pexels.com/photos/350772/pexels-photo-350772.jpeg',
'https://static.pexels.com/photos/289506/pexels-photo-289506.jpeg'
];
class App extends React.Component {
constructor(props) {
super(props);
const {links, images} = props;
this.state = {
linksWithImage: _.zipObject(links, images),
};
}
render() {
const {linksWithImage} = this.state;
return (
<div>
{_.map(linksWithImage, (image, link) => (
<a href={link}>
<img src={image} />
</a>
))}
</div>
);
}
}
ReactDOM.render(
<App links={links} images={images} />,
document.getElementById('app')
);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<div id="app"></div>
&#13;
答案 3 :(得分:0)
你应该像@Elie Gnrd建议的那样重组你的状态。使用包含一对链接和图像的对象数组:
{
href: 'https://www.google.com',
src: 'https://static.pexels.com/photos/380863/pexels-photo-380863.jpeg'
}
然后你可以像这样重构你的代码:
const Link = (link, img) => (
<a href={link}>
<img src={img} />
</a>
);
class LinkList extends React.Component {
constructor(props) {
super(props);
this.state = {links: props.links};
}
render() {
const {links} = this.props;
return (
{links.map(link => <Link {...link} />)}
);
}
}
这样,将链接传递到其他地方并更新状态会更容易。旁注:最佳做法是提取渲染逻辑,如&#34;如何使用图像渲染单个链接&#34;成为无国籍的功能组件。这样,您的代码将更易于阅读,测试和维护。