简体   繁体   English

如何在反应组件中添加和删除类名?

[英]How do I add and remove classNames in a react component?

I would like to implement something like this using React hooks:我想使用 React 钩子来实现这样的东西:

const header = document.querySelector(".nav-header");

function stickyHeader() {
  if (window.pageYOffset > 600) {
    header.classList.remove("header");
  } else {
    header.classList.add("header");
  }
}

window.addEventListener("scroll", () => {
  stickyHeader();
});

Above, is how I would have manipulated the DOM in vanilla js.以上是我在 vanilla js 中操作 DOM 的方式。 I would like to do the same for a component in react.我想对 react 中的组件做同样的事情。

className is an element attribute. className是一个元素属性。 Therefore you need to set it in your render component function like below:因此,您需要在render组件 function 中设置它,如下所示:

...
render() {
  let className = 'menu';
  if (this.props.isActive) {
    className += ' menu-active';
  }
  return <span className={className}>Menu</span>
}

here is an example on how to handle scroll events with React是一个关于如何使用 React 处理滚动事件的示例

Possibly try a getClassName method which returns a joined array of classes on every render可能尝试一个 getClassName 方法,该方法在每次渲染时返回一个连接的类数组

For a functional component对于功能组件

const getClassName = () => {
  let classes = ["nav"];

  if (window.pageYOffset > 600) {
   classes.push("header");
  } 
  //more conditions if required

  return classes.join(" ");
  //returns "nav header" || "nav"

}

and then in your component return method然后在你的组件返回方法中

return (
 <div className={getClassName()}><div>
)

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

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