如何在nextjs中通过其他元素的onClick修改元素?

import Link from 'next/link';


function myClick(e){

  console.log(e);

}


const Index = () => (

        <section className="min-vh-100">

            <div className="input_bar border rounded-maximum p-1 mx-1 bg-white d-flex">

                <input className="myButton submit_bar text-black" placeholder="Insert your input&hellip;"/>

                <Link href="#"><a onClick={myClick} className="input_icon"></a></Link>

            </div>

        </section>

);

我正在使用nextjs,并且试图通过另一个div中的click函数来更改div的类,我找不到如何执行此操作的示例,因此我可以理解它的工作原理。谢谢你。


哈士奇WWW
浏览 375回答 2
2回答

慕沐林林

这是使用引用的示例:import Link from 'next/link'const Index = () => {&nbsp; let myDiv = React.createRef()&nbsp; function myClick() {&nbsp; &nbsp; myDiv.current.classList.add('add-this-class')&nbsp; }&nbsp; return (&nbsp; &nbsp; <section className="min-vh-100">&nbsp; &nbsp; &nbsp; <div&nbsp; &nbsp; &nbsp; &nbsp; ref={myDiv}&nbsp; &nbsp; &nbsp; &nbsp; className="input_bar border rounded-maximum p-1 mx-1 bg-white d-flex"&nbsp; &nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; className="myButton submit_bar text-black"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder="Insert your input&hellip;"&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; <Link href="#">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a onClick={myClick} className="input_icon" />&nbsp; &nbsp; &nbsp; &nbsp; </Link>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </section>&nbsp; )}了解我在这里做什么。我正在使用此行创建参考:let myDiv = React.createRef()然后,将其分配给要访问的元素,在示例中,将其分配给div:<div ref={myDiv} className="..." >在onClick函数上,我访问div并添加一个类:myDiv.current.classList.add('add-this-class')让我知道这是否适合您。(如果确实如此,则感谢Abderrahman)

qq_花开花谢_0

我用钩子。const Index = () => {&nbsp; &nbsp; const [className, setClassName] = useState("")&nbsp; &nbsp; const myClick = () => {&nbsp; &nbsp; &nbsp; &nbsp; setClassName("some-class")&nbsp; &nbsp; }&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button onClick={myClick}>Click me</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div className={className}>Classname gets changes</div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript