首页 > web前端 > js教程 > 正文

shell 中的 Props 和回调

霞舞
发布: 2024-10-06 20:24:51
转载
1014人浏览过

shell 中的 props 和回调

在这篇博文中,我将带您了解一个实际场景,其中父组件 (listbox) 使用 props 和回调与子组件 (alertcomponent) 进行交互。

当您希望子组件与父组件通信以维护状态或触发操作时,这在 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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号