簡體   English   中英

在 React js 中單擊項目后如何顯示組件?

[英]How can I show a component after item clicked in react js?

所以為了讓事情變得清晰和簡單:
單擊我的 Add User Item后,我的AdminDash組件上顯示了一個AddUser組件,所有內容都顯示在我的 AdminDash 上,
我的AdminDash包含SideMenuSideMenu包含ItemsItems包含Item列表讓我向您展示樹:

  1. 添加用戶。

  2. 管理員破折號:

    • 側邊菜單:
      • 項目:
        1. 物品。
        2. 物品。
        3. 物品。

管理員破折號

//Some code
<SideMenu />
//Here where I want to show my addUser Component

側邊菜單

//Some code
<Items />

項目

//Some code
<Item Name="addUser" />
<Item Name="deleteUser" />
<Item Name="updateUser" />

物品

<ul>
  <li   
onClick={I WANT TO SHOW MY ADDUSER COMPONENT}
>
    <div> {props.Name} </div>
  </li>
</ul>

添加用戶

//Some random code 
<p> this is the add user component</p>

所以每當我點擊像 AddUser 這樣的項目時,我希望它的組件顯示在我的 Admin Dash 上,有什么提示嗎?

因此,經過多次嘗試和長期研究,我幾乎使用 useContext 來完成這項工作,但最終我找到了解決方案,這些是步驟:

  1. 首先,我添加了一個新組件<AdminOptions /> ,其中包含呈現我的<AddUser /><DeleteUser /><UpdateUsers />的所有邏輯。
  2. 我通過最后一個子 ( <Item /> ) 傳遞了一個函數來調用它並將一些參數傳遞給父組件<AdminDash />以告知單擊了哪個項目以及要呈現哪個項目。
  3. 然后我使用這些參數並將它們再次傳遞給我的新組件 ` 以呈現該特定項目,它有點復雜並且層次結構很多,但它對我來說是一個完美的解決方案。

管理員破折號

const[componentId, setComponentId]= React.useState(false);
const [show, setShowComponent] = React.useState(false);

const handleClick=(id)=>{
      if(id===componentId){
        setShowComponent(!show);
      }
      else{
        setComponentId(id);
        setShowComponent(true);
      }
    }
return (
//Here I pass the handleClick hooks to the childs
<SideMenu handleClick={handleClick} />
//my new component who will render the items component
<AdminOptions whatToShow={componentId} show={show}  />
);

側邊菜單

//passing again the handleClick to childs
<Items handleClick={props.handleClick} />

項目

//I'm passing again the handleClick and giving each item an ID to differentiate between them 
<Item 
  Name="addUser"
  Id="AddUser"
  handleClick={props.handleClick} />
<Item 
  Name="deleteUser"
  Id="DeleteUser"
  handleClick={props.handleClick} />
<Item 
  Name="updateUser"
  Id="UpdateUser"
  handleClick={props.handleClick} />

物品

<ul>
//here in the onClick i pass the function handleclick with an item id as a parameter
  <li   
onClick={()=>{props.handleClick(props.Id)}}
>
    <div> {props.Name} </div>
  </li>
</ul>

管理員選項

//So here is a switch case conditional rendering depending on Item's ID
switch (props.whatToShow){
            case "AddUser":
                return(props.show && <AddUser />);
            case "DeleteUser":
                return(props.show && <DeleteUser />);
            case "UpdateUser":
                return(props.show && <UpdateUser />);
            default :
                return (<> </>);

因此,當我單擊添加用戶項目時,它將該特定項目的 Id 傳遞給父組件(AdminDash),父組件(AdminDash)使用項目的 Id 執行該 handleClick,並使 AdminOptions 在 AdminDash 中顯示該項目組件,我盡力了為了盡可能清楚,任何有問題的人都可以在評論中留言。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM