返回

reactjs——为什么React组件卸载了,而jsx没有

发布时间:2022-05-12 23:55:44 364

我最近遇到了这种行为,并试图了解其原因。基本上,到目前为止我注意到的是 React 子组件将在其父组件的状态更改时被挂载和卸载。但是,包含相同子组件的 jsx 不会。

我把这个简化的例子放在一起来演示这种行为。

const Child = ({ title }) => {
  const [count, setCount] = React.useState(0);
  const increment = () => setCount((x) => x + 1);

  return (
    <button onClick={increment}>
      {title} Current count = {count}
    </button>
  );
};

const App = () => {
  const [, setState] = React.useState(false);
  const rerender = () => setState((x) => !x);

  const ChildWrapper = () => <Child title="Component" />;
  const childWrapperJsx = <Child title="jsx" />;

  return (
    <div>
      <button onClick={rerender}>Re render parent</button>
      <br />
      <ChildWrapper />
      {childWrapperJsx}
    </div>
  );
}
const domContainer = document.querySelector('#root');
const root = ReactDOM.createRoot(domContainer);
const e = React.createElement;
root.render(e(App));

<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script> <div id="root"></div>
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(1)
按点赞数排序
用户头像
相关帖子
下一篇
python-Tkinter中带有PyDub的音量滑块 2022-05-12 22:37:34