javascript - 希望在 React 中将文本放在图像上

我在 react 中有一个 Splideslide 元素,并且希望将描述文本移动到每个元素的图像上。目前我拥有的代码是:

import {useEffect, useState} from "react";
import styled from "styled-components";
import {Splide, SplideSlide} from "@splidejs/react-splide";
import "@splidejs/splide/dist/css/splide.min.css";

function Popular() {
    const [popular, setPopular] = useState([]);


    useEffect(() => {
        getPopular();
    }, []);
    
    const getPopular = async() => {
      const api = await fetch(`https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_API_KEY}&number=9`);
      const data = await api.json();
      console.log(data);
      setPopular(data.recipes)
      console.log(data.recipes)
      
    }

    return (
      <div>
        <Wrapper>
          <h3>Popular Picks</h3>
          <Splide options = {{
            perPage:4,
            arrows: false,
            pagination: false,
            drag: 'free',
            gap: "4rem",
          }}>
            {popular.map((recipe) =>{
              return (
                <SplideSlide>
                  <Card>
                    <Gradient/>
                    <p>{recipe.title}</p>
                    <img src={recipe.image} alt={recipe.title}/>
                    
                  </Card>
                </SplideSlide> 
              );
            })}
          </Splide>
        </Wrapper>  
      </div>
    )
}

const Wrapper = styled.div`
  margin: 4rem 0rem;
  postion: absolute;
`;

const Card = styled.div`
  min-height: 25rem;
  overflow: hidden;
  postion: relative;
  img {
    border-radius: 2rem;
    postion: absolute;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  p {
    position: absolute;
    z-index: 10;
    left: 50%;
    bottom: 0%;
    transform: translate(-50%, 0%);
    color: black;
    width: 100%;
    text-align: center;
    font-weight: 600;
    font-size: 1rem;
    height: 40%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
`;

const Gradient = styled.div`
  z-index: 3
  postion: absolute;
  width: 100%;
  height: 100%;
  background: linear-gradient(rgba(0,0,0,0), rgba(0,0,0,0.5))
`;
export default Popular

从理论上讲,我相信这应该能够移动图像上的文本,但由于某种原因它没有按预期工作。完整的项目可以在这里的存储库中看到:https://github.com/VirochaanRG/delicious。请随时发表评论以获取更多信息或任何澄清。

回答1

也许是因为你的多重

postion: absolute;

代替

position: absolute;

;)

相似文章

最新文章