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

问题描述 投票:0回答:3

试图在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

任何提示都会很可爱.. <3

javascript arrays reactjs
3个回答
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
投票

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

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

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

或者,如@Shubham所建议的那样,使用一个将返回所需样式对象的方法:

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

在渲染中:

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

0
投票
{ post.featured_image_src 
  ? <a href={post.link}>
       <div className="post-img" style={{backgroundImage: `url(${post.featured_image_src})`}}/>
    </a>
  : null
}
© www.soinside.com 2019 - 2024. All rights reserved.