使用 React hook 从一个组件切换到另一个组件

Toggle one component from another using React hook

我有两个 child 组件,我希望其中一个组件中有一个按钮可以切换 (on/off) 另一个组件中的 html。我看过有关提升状态和组件之间通信的教程,但其中大部分与移动数据有关。我想从另一个操作一个组件。我希望使用 useState 实现这一点,如果可能的话不使用 useContext。谢谢!

PARENT

import React from "react";

function App() {
  return (
    <div>
      <AppProvider>
        <ComponentOne/>
        <Slideshow />
        <ComponentTwo/ >
      </AppProvider>
    </div>
  );

} 

CHILD 1




export default function ComponentOne() {
 

  return (
    <div>
      <button>The button that toggles</button>
    </div>
  );
}

CHILD 2




export default function ComponentTwo() {
 

  return (
    <div>
      <div>The content that hides/shows</div>
    </div>
  );
}

您需要使用 state 来切换值。将状态作为道具传递给 ComponentTwo,并将状态更新函数作为回调函数作为道具传递给 ComponentOne

import React , { useState, useCallback } from 'react';

function ComponentOne({ onToggle}) {
  return (
    <div>
      <button onClick={onToggle}>The button that toggles</button>
    </div>
  );
}

function ComponentTwo({show}) {

  return (
    <div>
     {show && <div>The content that hides/shows</div>} 
    </div>
  );
}

export default function App() {
  const [show, setShow ] = useState(true);

  const handleToggle = useCallback(() => setShow(prevShow => !prevShow),[])

  return (
    <div className="App">
      <ComponentOne onToggle={handleToggle} />
      <ComponentTwo show={show} />
    </div>
  );
}

参考

useState

useCallback