简体   繁体   中英

Manipulating the DOM in React

I have been trying to learn React lately and have a question about direct DOM manipulation. I'm working on a project where upon page load, a logo slides in from the side. I can accomplish this in vanilla javascript, but this particular project is in React. I'm wondering if it is okay to do the following? Or if there is a preferred way to do it in React?

I have the following function:

logoSlideIn() {
  const logo = this.refs.logo;
  logo.classList.add("z-logo-reveal");
}

In the componentDidMount method, I have:

setTimeout(this.logoSlideIn, 500);

The corresponding CSS is:

.z-logo {
  position: relative;
  background: url(z-logo.svg) bottom center no-repeat;
  background-size: contain;
  height: 35%;
  width: 50%;
  left: 1800px;
  transition: 4s ease-in-out;
}


.z-logo-reveal {
  left: 0;
}

It works, but is there a better way?

In react it's very rarely when you really need to manipulate the DOM directly. usually is considered not a good practice, for your particular case I'd recommend using props to assign the new className, for example:

state = {
  animateCls: '',
};

componentDidMount() {
  setTimeout(() => this.setState({ animateCls: 'z-logo-reveal'}), 500);
}

render() {
  const { animateCls } = this.state;

  return (
    <div className={animateCls}>
    </div>
  );
}

您所拥有的一切都很好,您也可以通过设置props来做到,这将是相似的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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