给元素分配ID并在useEffect和函数之外进行控制台输出不起作用。

huangapple go评论74阅读模式
英文:

Giving id to element and consoling not working outside of useEffect and functions

问题

我有这个组件



import { useState, useEffect } from "react"

export default function profile() {

  const [text, setT] = useState("")

  const f = () => console.log(hiop)

  const t = "hi boy how r u "

  function type(s = 100, i = 0, d = 0) {

    setInterval(() => (

      d == 0 ? i++ : i--,

      i >= t.length && d == 0 ? d = 1 : i == 0 ? d = 0 : 0,

      setT(t.slice(0, i))), s)

  }

  useEffect(() => {

    type()

    console.log(hiop)

  }, [])

  return (

    <h1 id="hiop" onClick={f}>{text}</h1>

  )

}
英文:

I have thid component



import { useState, useEffect } from &quot;react&quot;

export default function profile() {

  const [text, setT] = useState(&quot;&quot;)

  const f = () =&gt; console.log(hiop)

  const t = &quot;hi boy how r u &quot;

  function type(s = 100, i = 0, d = 0) {

    setInterval(() =&gt; (

      d == 0 ? i++ : i--,

      i &gt;= t.length &amp;&amp; d == 0 ? d = 1 : i == 0 ? d = 0 : 0,

      setT(t.slice(0, i))), s)

  }

  useEffect(() =&gt; {

    type()

    console.log(hiop)

  }, [])

  return (

    &lt;h1 id=&quot;hiop&quot; onClick={f}&gt;{text}&lt;/h1&gt;

  )

}

Can anybody tell me why its not working outside of useEffect and callback functions when I console the hiop element and why does it work when I put this console in useEffect and callback functions like onclick onsubmit

答案1

得分: 2

当您在第6行调用函数f时,它确实起作用,并且当您单击h1时调用它,它会记录。

尝试在将来使变量名称更清晰。

英文:

It really works when you invoke the function f in line 6 and it's called when you click your h1 and it logs

Try to make variables names more clear for yourself in the future

huangapple
  • 本文由 发表于 2023年8月5日 13:32:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76840280.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定