首頁 > web前端 > js教程 > 主體

shell 中的 Props 與回呼

Linda Hamilton
發布: 2024-10-02 06:28:30
原創
138 人瀏覽過

Props and Callbacks in a shell

在這篇博文中,我將帶您了解一個實際場景,其中父組件(ListBox) 與子組件(AlertComponent ) 使用props 和回呼。

當您希望子元件與父元件通訊以維護狀態或觸發操作時,這在 React 中非常有用。

讓我們透過這個例子來理解:

  • 我有一個 ListBox 元件,用於顯示項目清單。當使用者長按任何項目時,會出現警告對話框,詢問使用者是否要刪除該項目。

以下是交互細分:

  1. ListBox(父級)渲染項目並將必要的道具和回呼傳遞給 AlertComponent(子級)。
import React, { useState } from 'react';
import AlertComponent from './AlertComponent';

const ListBox = () => {
  const [showComponent, setShowComponent] = useState<boolean>(false);

  const alertAction = async () => {
    setShowComponent(!showComponent);
  };

  return (
    <div>
      <div onLongPress={alertAction}>
        <p>Item 1</p>
        {/* Other list items */}
      </div>

      {/* Passing props to the child component */}
      <AlertComponent
        title="Deleting item?"
        description="Click Accept to delete."
        onAccept={() => {
          alert('Item Deleted');
          setShowComponent(false);
        }}
        onCancel={() => setShowComponent(false)}
        showComponent={alertAction}

      />
    </div>
  );
};

export default ListBox;
登入後複製
  1. AlertComponent 接受標題、描述和回呼等屬性,例如 onAcceptonCancel 和狀態變更屬性 showComponent
export const AlertComponent: = ({ title, description, 
onAccept, onCancel, showComponent }) => {
return (<AlertDialog>
... rest of the code
</AlertDialog>)
}
登入後複製
  1. 父元件需要管理對話框的可見性,子元件透過回呼發出事件來與父元件互動以切換此可見性。

showComponent 作為回調工作,因為它維護負責顯示/隱藏 AlertComponent

的狀態

每當按下 Reject 時,此回呼將切換 showComponent 的目前狀態。

<AlertComponent
        title="Deleting item?"
        description="Click Accept to delete."
        onAccept={() => {
          alert('Item Deleted');
          setShowComponent(false);
        }}
        onCancel={() => setShowComponent(false)}
        showComponent={alertAction}
      />
登入後複製

以這種方式使用 propscallbacks 可以讓 React 中父元件和子元件之間的資料清晰流動。

父級可以控制狀態並將其傳遞給子級,而子級可以透過回調進行通信,以通知父級用戶執行的任何更改或操作。

這對於顯示警報、模式或彈出視窗以響應用戶互動等場景特別有用。

繼續建造!

以上是shell 中的 Props 與回呼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!