React.js:在map函数中将图像设置为div背景

时间:2017-12-21 11:13:41

标签: javascript arrays reactjs

尝试在React.js项目中将图像设置为地图函数内的div背景,但我无法访问 post.featured_image_src 外部地图功能并在 divStyle中设置为背景变量:

class Archive extends Component {
    render() {
        let allPosts = DataStore.getAllPosts();
        let pageData = DataStore.getPageBySlug('archive');
        let acf = pageData.acf;

        const divStyle = {
          backgroundImage: 'url(' + post.featured_image_src + ')'
        }

        return (
            <div>
                <h1>{pageData.title.rendered}</h1>
                <div className="post-container">
                  <div className="post-wrapper">
                    {allPosts.map((post, i) => {
                      return (
                        <div className="post" key={i}>
                          {post.featured_image_src
                            ? <a href={post.link}><div style={divStyle}/></a>
                            : null}
                          <h3 className="post-title"><a href={post.link} dangerouslySetInnerHTML={{__html:post.title.rendered}} /></h3>
                        </div>
                      )
                    }
                  )}
                </div>
              </div>
            </div>
        );
    }
}

enter image description here

任何提示都会非常可爱..&lt; 3

3 个答案:

答案 0 :(得分:4)

问题是当您尝试访问它以定义样式时未定义post

  const divStyle = {
      backgroundImage: 'url(' + post.featured_image_src + ')'
    }

你可以将这个逻辑作为一个函数移动

     const divStyle = (src) => ({
      backgroundImage: 'url(' + src + ')'
    })

    return (
        <div>
            <h1>{pageData.title.rendered}</h1>
            <div className="post-container">
              <div className="post-wrapper">
                {allPosts.map((post, i) => {
                  return (
                    <div className="post" key={i}>
                      {post.featured_image_src
                        ? <a href={post.link}><div style={divStyle(post.featured_image_src)}/></a>
                        : null}
                      <h3 className="post-title"><a href={post.link} dangerouslySetInnerHTML={{__html:post.title.rendered}} /></h3>
                    </div>
                  )
                }
              )}
            </div>
          </div>
        </div>
    );

答案 1 :(得分:1)

出于显而易见的原因,您无法在定义之前使用变量。

您可以将<div style={divStyle}/>替换为:

<div style={ backgroundImage: "url(" + post.featured_image_src + ")" } />
@Shubham建议

OR 使用一种方法返回所需的样式对象:

const divStyle = (imgSrc) => ({
  backgroundImage: `url(${imgSrc})`
})

在渲染中:

<div style={this.divStyle(post.featured_image_src)}/>

答案 2 :(得分:0)

{ post.featured_image_src 
  ? <a href={post.link}>
       <div className="post-img" style={{backgroundImage: `url(${post.featured_image_src})`}}/>
    </a>
  : null
}