代码之家  ›  专栏  ›  技术社区  ›  Aslan

在其内部调用React组件

  •  0
  • Aslan  · 技术社区  · 3 年前

    这更多的是一个理论问题,我们在这种情况下使用状态,但让我们说:既然每个React组件都是一个函数,为什么当我们像下面的例子一样在其内部调用它时,什么都不会发生。调用函数难道不应该导致组件再次呈现自己吗?

    const CallComp = () => {
      let title = "Not clicked yet.";
      const clickHandler = () => {
        title = "Clicked!";
        CallComp();
      };
      return (
        <>
          <div>{title}</div>
          <button onClick={clickHandler}>Test</button>
        </>
      );
    };
    
    export default CallComp; 
    
    2 回复  |  直到 3 年前
        1
  •  0
  •   ruakh    3 年前

    渲染函数通常没有副作用;特别是,它没有在页面上实际安装组件的副作用。相反,render函数由React调用,它将信息返回给React,告诉它显示什么。如果渲染函数不是由React调用的,那么这没有任何效果,除非它的调用方决定对渲染函数返回的内容执行某些操作。

        2
  •  -1
  •   Fahim Shahriyar Chowdhury    3 年前

    不能调用react函数本身,因为它违反了react钩子的规则

    如果您想重新发送组件,请使用useState();

    import "./styles.css";
    import {useState} from "react" // import useState
    
    export default function App() {
      return (
        <CallComp/>
      );
    }
    const CallComp = () => {
      // let title = "Not clicked yet."; this does not cause a re-render
      const [title, setTitle] = useState("Not clicked yet."); // so you need to use useState if you want to re-render
      const clickHandler = () => {
        setTitle("Clicked!")
        // CallComp(); this line breaks the rules of react hooks
      };
      return (
        <>
          <div>{title}</div>
          <button onClick={clickHandler}>Test</button>
        </>
      );
    };