首页  >  文章  >  web前端  >  shell 中的 Props 和回调

shell 中的 Props 和回调

Linda Hamilton
Linda Hamilton原创
2024-10-02 06:28:30140浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn