ReactJS - Создание ссылок и доступ к элементам DOM для использования полной страницы. js - PullRequest
0 голосов
/ 28 января 2020

Я пытаюсь перенести код, созданный в JS / JQuery, на ReactJS. Код использует полную страницу библиотеки. js. Цель состоит в том, чтобы изменить название в соответствии с разделом о фокусе. Я изо всех сил пытаюсь правильно захватить свойства элементов в DOM, используя ссылки. Я пытался следовать документации ReactJS, но пример в документации сделал все более запутанным.

Мой вопрос: как я могу сохранить эти свойства и затем применить их, используя CSS к требуемому элементу DOM? Заранее спасибо.

Псевдокод

  • Ширина заголовка магазина
  • Высота заголовка магазина
  • Примените эти свойства к рамка и маска родителей
  • Прослушайте события прокрутки на полной странице. js и соответственно переведите позицию заголовка

Codepen (JS / JQuery)

$(document).ready(function() {
  var titleWidth = $(".title").outerWidth();
  var titleHeight = $(".title").outerHeight();
  $("#mask").css({ height: titleHeight + "px", width: titleWidth + "px" });
  $("#frame").css("top", titleHeight);

  new fullpage("#fullpage", {
    sectionsColor: ["yellow", "orange", "#C0C0C0", "#ADD8E6"],
    afterRender: function() {
      $("#frame").transition({ top: "-=" + titleHeight, delay: 1000 });
    },
    onLeave: function(origin, destination, direction) {
      var leavingSection = this;

      //after leaving section 2
      if (direction == "down") {
        $("#frame").transition({ top: "-=" + titleHeight });
      } else if (direction == "up") {
        $("#frame").transition({ top: "+=" + titleHeight });
      }
    }
  });
});

Codesandbox (ReactJS)

import React from "react";
import ReactDOM from "react-dom";
import "fullpage.js/vendors/scrolloverflow"; // Optional. When using scrollOverflow:true
import ReactFullpage from "@fullpage/react-fullpage";

import "./styles.css";

class MySection extends React.Component {
  render() {
    return (
      <div className="section">
        <h3>{this.props.content}</h3>
      </div>
    );
  }
}

const anchors = ["firstPage", "secondPage", "thirdPage"];

const FullpageWrapper = () => (
  <ReactFullpage
    anchors={anchors}
    navigation
    navigationTooltips={anchors}
    sectionsColor={["#282c34", "#ff5f45", "#0798ec"]}
    onLeave={(origin, destination, direction) => {
      console.log("onLeave event", { origin, destination, direction });

      //after leaving section 2
      if (origin.index === 1 && direction === "down") {
        alert("Going to section 3!");
      } else if (origin.index === 1 && direction === "up") {
        alert("Going to section 1!");
      }
    }}
    render={({ state, fullpageApi }) => {
      console.log("render prop change", state, fullpageApi); // eslint-disable-line no-console

      return (
        <div>
          <MySection content={"Slide down!"} />
          <MySection content={"Keep going!"} />
          <MySection content={"Slide up!"} />
        </div>
      );
    }}
  />
);

class Index extends React.Component {
  constructor(props) {
    super(props);
    this.title = React.createRef();

    // this.title = null;
    // this.titleRef = element => {
    //   this.title = element;
    // };
    // this.setTitle = () => {
    // Focus the text input using the raw DOM API
    // if (this.title) this.title.current.offsetWidth;
    // };
  }

  componentDidMount() {
    // console.log(this.setTitle())
    const titleWidth = this.title.current.offsetWidth;
    const titleHeight = this.title.current.offsetHeight;
    console.log(titleWidth, titleHeight);
  }

  render() {
    return (
      <div class="wrapper">
        <div id="mask">
          <div id="frame">
            <h1 ref={this.title} class="title">
              One
            </h1>
            <h1 ref={this.title} class="title">
              Two
            </h1>
            <h1 ref={this.title} class="title">
              Three
            </h1>
            <h1 ref={this.title} class="title">
              Four
            </h1>
          </div>
        </div>
        <div class="content">
          <FullpageWrapper />
        </div>
      </div>
    );
  }
}

ReactDOM.render(<Index />, document.getElementById("react-root"));
...