如何在 React / Next js 中添加基于函数的 css 类?

我正在使用 Next js 和反应可见性传感器来让我知道 div 何时在屏幕上可见。


代码有点像:


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>

);

}

将 div className 更改为 {colorstate} 变量不起作用(返回未定义)。


我是 React 的新手,我使用“this.state”方法在线尝试了各种答案,但都没有用。


现在 onChange 函数工作正常并在日志中打印正确的类名,我只是不知道如何将它与 div 相关联。


谢谢。


慕容3067478
浏览 82回答 2
2回答

慕神8447489

您可以使用 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) => {&nbsp; isVisible ? setColorState("test") : setColorState("test dark");}&nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <VisibilitySensor onChange={onChange}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div className={colorState}>this is a test div.</div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </VisibilitySensor>);}

MMMHUHU

似乎您的 colorState 变量只能通过 onChange 可见。class Home extends React.Component{&nbsp; &nbsp; constructor(props){&nbsp; &nbsp; &nbsp; &nbsp; super(props);&nbsp; &nbsp; &nbsp; &nbsp; this.state =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dark: true&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; test = () => {&nbsp; &nbsp; &nbsp; &nbsp; this.setState(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dark: !this.state.dark&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }&nbsp; &nbsp; render(){&nbsp; &nbsp; &nbsp; &nbsp; return(&nbsp; &nbsp; &nbsp; &nbsp; <div className={this.state.dark ? "dark" : "white"} onClick={this.test}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; test&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }}应该管用
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript