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

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

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

问题

我有这个组件

  1. import { useState, useEffect } from "react"
  2. export default function profile() {
  3. const [text, setT] = useState("")
  4. const f = () => console.log(hiop)
  5. const t = "hi boy how r u "
  6. function type(s = 100, i = 0, d = 0) {
  7. setInterval(() => (
  8. d == 0 ? i++ : i--,
  9. i >= t.length && d == 0 ? d = 1 : i == 0 ? d = 0 : 0,
  10. setT(t.slice(0, i))), s)
  11. }
  12. useEffect(() => {
  13. type()
  14. console.log(hiop)
  15. }, [])
  16. return (
  17. <h1 id="hiop" onClick={f}>{text}</h1>
  18. )
  19. }
英文:

I have thid component

  1. import { useState, useEffect } from &quot;react&quot;
  2. export default function profile() {
  3. const [text, setT] = useState(&quot;&quot;)
  4. const f = () =&gt; console.log(hiop)
  5. const t = &quot;hi boy how r u &quot;
  6. function type(s = 100, i = 0, d = 0) {
  7. setInterval(() =&gt; (
  8. d == 0 ? i++ : i--,
  9. i &gt;= t.length &amp;&amp; d == 0 ? d = 1 : i == 0 ? d = 0 : 0,
  10. setT(t.slice(0, i))), s)
  11. }
  12. useEffect(() =&gt; {
  13. type()
  14. console.log(hiop)
  15. }, [])
  16. return (
  17. &lt;h1 id=&quot;hiop&quot; onClick={f}&gt;{text}&lt;/h1&gt;
  18. )
  19. }

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:

确定