在react中重用组件并告诉组件要更改状态的哪个键:值

发布于 2025-01-16 07:38:31 字数 1130 浏览 2 评论 0原文

我在弄清楚如何在许多地方重用组件方面遇到了一些困难。

显然,React 如此优秀的原因是因为您可以创建通用组件并在许多不同的页面中重用它们,或者只是在同一页面中多次重用它们。

我有这个组件用于显示一个下拉列表,用户可以使用该下拉列表选择新值并更改其设置。该组件在我网站上的许多不同地方重复使用。

                  <ChannelSelect
                    channelID={
                      saveEnabled.saveEnabled.newSettings.verificationPanel.channelID
                    }
                    settings={
                      saveEnabled.saveEnabled.newSettings.verificationPanel.channelID
                    }
                  />

我正在努力解决的是告诉这个组件要更改状态(对象)中的哪个key: value。这是因为仅仅传递下面的代码实际上并不允许我更改这个特定键的状态。

settings={saveEnabled.saveEnabled.newSettings.verificationPanel.channelID}

在我的选择菜单 onChange 事件中,我有下面的代码片段。但是,这实际上不允许我更改特定值声明,它实际上只会覆盖整个对象。

 const { saveEnabled, setSaveEnabled } = useContext(SaveContext);
 const onChange = (event) => {
   props.settings = "newValue"
   setSaveEnabled(props.settings)    

知道我该怎么做吗?

I'm having a little bit of difficulty figuring out how to reuse components in many places.

Obviously the reason why react is so good is because you can create common components and reuse them across many different pages, or just multiple times in the same page.

I have this component for displaying a dropdown that a user can use to select a new value, and change their settings. This component is reused in many different places on my website.

                  <ChannelSelect
                    channelID={
                      saveEnabled.saveEnabled.newSettings.verificationPanel.channelID
                    }
                    settings={
                      saveEnabled.saveEnabled.newSettings.verificationPanel.channelID
                    }
                  />

What I am struggling with is telling this component which key: value in the state (object) to change. This is because simply passing in the code below, doesn't actually allow me to change the state of this specific key.

settings={saveEnabled.saveEnabled.newSettings.verificationPanel.channelID}

In my select menus onChange event I have the code snippet below. However, this doesn't actually allow me to change the specific value declare, it would actually just overwrite the whole object.

 const { saveEnabled, setSaveEnabled } = useContext(SaveContext);
 const onChange = (event) => {
   props.settings = "newValue"
   setSaveEnabled(props.settings)    

Any idea how I can do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文