简体   繁体   English

从兄弟组件 React hooks 调用 function

[英]Call function from sibling component React hooks

How can I call a function that belongs to a sibling component either with props or context?我如何调用 function 属于具有道具或上下文的兄弟组件?

I've been trying to to this using props and context but I'm getting confused because I'm not passing variables but an actual function with parameters我一直在尝试使用道具和上下文来做到这一点,但我感到困惑,因为我没有传递变量,而是传递带有参数的实际 function

I want to call the function handleSelectedUser that is inside the List component when I click the delete button in the Card component当我单击 Card 组件中的删除按钮时,我想调用 List 组件内的 function handleSelectedUser

Here it is in action in Replit这是在Replit中运行的

here is my code这是我的代码

App component:应用组件:

function App() {
  const [currentUser, setCurrentUser] = useState(null)
  
   
  return (
    <main>
        <List 
          setCurrentUser={setCurrentUser} />
        <Card 
          currentUser={currentUser} 
          setCurrentUser={setCurrentUser}
          />
    </main>  );
}

List Component列表组件

function List({setCurrentUser}) {
  const [users, setUsers] = useState([])

  useEffect(() => {
    getUsers()
  }, [])

  async function getUsers(){
    const apiUrl = "https://randomuser.me/api?results=40"
    const result = await fetch(apiUrl)
    const data = await result.json()
    setUsers(data.results)
  }

  function handleDeleteSelectedUser(userToDelete){
    users.filter(user => user.phone != userToDelete.phone)
  }

  function handleSelectedUser(selectedUser){
    setCurrentUser(selectedUser)
  }
  
  
  return(
    <>
      <div>
        <h1>List</h1>
        {
          users.map((user) => 
          <li onClick={() => handleSelectedUser(user)} key={user.phone}>
          {user.name.first} {user.name.last}</li>)
        }
      </div>
    </>
  )
}

Card Component卡片组件

function Card({currentUser, setCurrentUser}){
  
  function handleDelete(user){
    //Call handleSelectedUser in <List />
    setCurrentUser(null)
  }
  
  return (
    <div className="container">
      {currentUser && 
      <>
        <h2>{currentUser.name.first}'s Details</h2>
        <p>{currentUser.phone}</p>
        <button onClick={() => handleDelete(currentUser)}>Delete</button>
      </>
      }
    </div>
  )
}

If you're trying to "listen" for changes in a sibling component, a common approach is to use a shared prop as a hook dependency in the sibling.如果您试图“监听”兄弟组件中的更改,一种常见的方法是使用共享属性作为兄弟组件中的钩子依赖项。

For example:例如:

function List({ currentUser, setCurrentUser }) {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    getUsers();
  }, []);

  async function getUsers() {
    const apiUrl = "https://randomuser.me/api?results=40";
    const result = await fetch(apiUrl);
    const data = await result.json();
    setUsers(data.results);
  }

  function handleDeleteSelectedUser(userToDelete) {
    users.filter((user) => user.phone != userToDelete.phone);
  }

  function handleSelectedUser(selectedUser) {
    setCurrentUser(selectedUser);
  }

  useEffect(() => {
    // do something when currentUser changes
    handleSelectedUser(currentUser);
  }, [currentUser]);

  return (
    <>
      <div>
        <h1>List</h1>
        {users.map((user) => (
          <li onClick={() => handleSelectedUser(user)} key={user.phone}>
            {user.name.first} {user.name.last}
          </li>
        ))}
      </div>
    </>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM