使用状态对组件进行动态样式化

时间:2020-07-15 08:46:01

标签: javascript css reactjs

嗨,我正在尝试向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;

1 个答案:

答案 0 :(得分:0)

问题

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

解决方案

定义初始状态

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

Edit matrix3d scrolling marquee