简体   繁体   English

使用 state 在反应组件中动态样式化元素

[英]Dynamically styling element in react component using state

Hi I am trying to add a matrix3d value to the h1 which will update on scroll and move the h1, however it doesn't seem to have any effect a but I can see in the console log that the values are indeed changing when I log this.state.transform, can anyone advice me on where I'm going wrong please嗨,我正在尝试向 h1 添加一个 matrix3d 值,该值将在滚动时更新并移动 h1,但是它似乎没有任何效果,但我可以在控制台日志中看到当我登录时这些值确实在变化this.state.transform,谁能告诉我我哪里出错了

import styles from "./marquee.module.scss";

class Marquee extends Component {
  componentDidMount() {
    window.addEventListener("scroll", this.renderMatrix, { passive: true });
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this.renderMatrix);
  }

  renderMatrix = () => {
    const distanceFromTop = window.pageYOffset;
    this.setState({
      transform: `matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, ${distanceFromTop}, 0, 0, 1)`,
    });
    console.log(this.state.transform)
  };

  render() {
    return (
      <div>
        <h1 className={styles.marquee} style={{ transform: this.state.transform }}>
          DESIGNER UI DESIGNER UI DESIGNER
        </h1>
        <h2>DESIGNER UI DESIGNER UI DESIGNER</h2>
        <h2>DESIGNER UI DESIGNER UI DESIGNER</h2>
      </div>
    );
  }
}

export default Marquee;

Issue问题

this.state.transform is initially undefined, so style={{ transform: this.state.transform }} fails. this.state.transform最初是未定义的,所以style={{ transform: this.state.transform }}失败。

Solution解决方案

Define initial state定义初始 state

state = {
  transform: `matrix3d(
    1, 0, 0, 0, 
    0, 1, 0, 0, 
    0, 0, 1, 0, 
    0, 0, 0, 1)`,
}

编辑 matrix3d 滚动选取框

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM