gpt4 book ai didi

javascript - 仅将静态样式分配给每个渲染组件一次

转载 作者:行者123 更新时间:2023-12-02 21:48:11 24 4
gpt4 key购买 nike

有没有一种方法可以让我将我的风格仅应用到每个单独的卡片图像一次。例如,我通过函数为 css 分配变换样式;我希望图像保留原始值,但是当渲染新组件时,该卡应该应用不同的变换值,但不应重新渲染原始现有组件样式。目前,所有变换样式都用不同的值重新渲染,这在 react 中的功能组件中可能吗?根据我在 Card 函数中放置当前变量的位置,所有值都会不断变化,在 Card 函数之外,值是静态的,并且卡片显示在彼此的顶部,因此您只能看到一张卡片。

const getStyle = () => {
let angle = Math.random() * 90 - 45
let xPos = Math.random() * 40 - 20
let yPos = Math.random() * 40 - 20
let transform = `translate(${xPos}px, ${yPos}px) rotate(${angle}deg)`
return transform
}


const Card = (props) => {
let current = getStyle()
return (
<img style={{ transform: current }} className="Card" alt={props.name} src={props.cardImg} />
)
}

最佳答案

使用useMemo .

const Card = (props) => {
let current = useMemo(getStyle, [])
return (
<img style={{ transform: current }} className="Card" alt={props.name} src={props.cardImg} />
)
}

关于javascript - 仅将静态样式分配给每个渲染组件一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60197482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com