简体   繁体   English

如何在 React / Next js 中基于 function 添加 css class?

[英]How to add css class based on function in React / Next js?

I'm using Next js and react visibility sensor to let me know when a div is visible on screen.我正在使用 Next js 并对可见性传感器做出反应,让我知道 div 何时在屏幕上可见。

Code kinda looks like:代码有点像:

import VisibilitySensor from "react-visibility-sensor";


function onChange(isVisible) {
  let colorstate = isVisible ? "test" : "test dark";
  console.log(colorstate)
}

export default function Home() {
  return (
              <VisibilitySensor onChange={onChange}>

                <div className={colorstate}>this is a test div.</div>

              </VisibilitySensor>
);
}

Changing the div className to the {colorstate} variable doesn't work (returns undefined).将 div className 更改为 {colorstate} 变量不起作用(返回未定义)。

I'm fairly new to React and I tried various answers online using "this.state" methods which all didn't work.我对 React 还很陌生,我使用“this.state”方法在线尝试了各种答案,但都不起作用。

Right now the onChange function works fine and prints the correct class name in the log, I just don't know how to associate it with the div.现在 onChange function 工作正常并在日志中打印正确的 class 名称,我只是不知道如何将它与 div 关联。

Thanks.谢谢。

You can use useState hook, this is how it would look like with initial className of 'test dark'您可以使用 useState 挂钩,这就是初始 className 为“test dark”时的样子

import VisibilitySensor from "react-visibility-sensor";
import {useState} from 'react'

export default function Home() {
const [colorState, setColorState] = useState('test dark')

const onChange = (isVisible) => {
  isVisible ? setColorState("test") : setColorState("test dark");
}

  return (
              <VisibilitySensor onChange={onChange}>

                <div className={colorState}>this is a test div.</div>

              </VisibilitySensor>
);
}

seems your colorState variable is visible only through the onChange.似乎您的 colorState 变量仅通过 onChange 可见。

class Home extends React.Component{

    constructor(props){
        super(props);
        this.state = 
        {
            dark: true
        }
        
    }

    test = () => {
        this.setState(
            {
                dark: !this.state.dark
            }
        )
    }

    render(){
        return(
        <div className={this.state.dark ? "dark" : "white"} onClick={this.test}>
            test
        </div>
        );
    }
}

should work应该管用

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

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