映射图像连接字符串

时间:2016-09-29 13:54:08

标签: javascript reactjs

我正在使用map函数迭代带有图像的数组。然后我试图在页面上显示这些图像。

您将看到图像被连接成一个污点。有谁知道如何做到这一点,我可以显示每个人的形象?

I have set up a jsfiddle here

请参阅下面的React代码:

var App = React.createClass({
    render: function(){
    var images = [
         {
            id:"1",
            images:['https://i.scdn.co/image/dc284fcd7e581aa2b7ca56f28c7c74f0ca0ad393', 'https://i.scdn.co/image/97ffc63dd5abfe7203d8f5e90d1a74427ac756e7']
         },
         {
            id:"2",
            images:['https://i.scdn.co/image/97ffc63dd5abfe7203d8f5e90d1a74427ac756e7', 'https://i.scdn.co/image/97ffc63dd5abfe7203d8f5e90d1a74427ac756e7']
         }
      ];
      return(<List images={images} />)
   }
});

var List = React.createClass({
    render: function() {
        var images = this.props.images.map(function(image){
            return(image.images[0]); // updated here
        })
        return(
            <div>
                <img src={images}></img>
                <p>{images}</p>
            </div>
        )       
    }
});

ReactDOM.render(
  <App name="World" />,
  document.getElementById('container')
);

1 个答案:

答案 0 :(得分:0)

以下是否有效? https://jsfiddle.net/petebere/19fmn5qs/

更改是添加<img />标记并将src属性设置为网址:

        var images = this.props.images.map(function(image, index){
            return <img key={index} src={(image.images[0])} />;
        });

此外,您现在不需要在最终<img />声明中使用return标记。请看我更新的小提琴。我还在React文档中添加了关键属性:https://facebook.github.io/react/docs/multiple-components.html#dynamic-children

完整代码:

var App = React.createClass({
    render: function() {
      var images = [
         {
            id:"1",
            images:['https://i.scdn.co/image/dc284fcd7e581aa2b7ca56f28c7c74f0ca0ad393', 'https://i.scdn.co/image/97ffc63dd5abfe7203d8f5e90d1a74427ac756e7']
         },
         {
            id:"2",
            images:['https://i.scdn.co/image/97ffc63dd5abfe7203d8f5e90d1a74427ac756e7', 'https://i.scdn.co/image/97ffc63dd5abfe7203d8f5e90d1a74427ac756e7']
         }
      ];

     return(<List images={images} />);
   }
});

var List = React.createClass({
    render: function() {
        var images = this.props.images.map(function(image, index){
            return <img key={index} src={(image.images[0])} />;
        });
        return(
            <div>
                <p>Your images</p>
                {images}              
            </div>
        );       
    }
});

ReactDOM.render(
  <App name="World" />,
  document.getElementById('container')
);