微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有条件地添加属性样式以响应元素

如何解决有条件地添加属性样式以响应元素

是否可以有条件地在for循环中添加样式属性。这种样式会在组件安装后立即添加到我的元素中,但是我希望仅当animateLighttrue就是this.props

时才添加属性
class Main extends Component {


    render() {

        const {animateLight} = this.props;
        const points1 = [];
        const points2 = [];
        const points3 = [];



        for (let i = 0; i < 10; i++) {
           points1.push( <img src={point1} key={i}
                        className={animateLight ? styles.pointsAppear : styles.points }
                        style={{ transform: `translate3d( ${Math.random() * 50 * i}px,${Math.random() * 50 * i}px,0 )` }}
                              alt="point"/>)

            points2.push(<img src={point2}
                            className={animateLight ? styles.pointsAppear : styles.points}
                            style={{ transform: `translate3d( ${Math.random() * 50 * i}px,0 )` }}
                              alt="point"/>)
            points3.push(<img src={point3}
                            className={animateLight ? styles.pointsAppear : styles.points}
                            style={{ transform: `translate3d( ${Math.random() * 50 * i}px,0 )` }}
                              alt="point"/>)
            }

        return (
            <div className={styles.containerMain}>
                <div className={styles.smallContainer}>
                    <div className={cx(styles.motivContainer,{ [styles.animateText]: animateLight})}>
                        <p className={styles.motivText}>
                            ...
                        </p>
                    </div>
                    <div className={styles.bulb}>
                        <img src={bulbLight}
                            className={cx(styles.motivImgLight,{[styles.lightAnimation]: animateLight}
                                        )}
                            alt="web idea" />

                            {points1}
                            {points2}
                            {points3}
                    </div>
                </div>
            </div>
        );
    }
}

解决方法

您可以做这样的事情

const styleProps = !animateLight ? {} : { style: { transform: `translate3d( ${Math.random() * 50 * i}px,${Math.random() * 50 * i}px,0 )` } };

<img {...styleprops} />

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。