gpt4 book ai didi

javascript - 为什么我的 React 应用程序中的两个点击事件会同时运行?

转载 作者:行者123 更新时间:2023-12-04 12:21:07 25 4
gpt4 key购买 nike

我有两个用户设置选项。一个是“启用级联面板”,另一个是“包含附件”。
我已经设置了状态变量和切换函数以传递给子组件,这样当我单击任一时,父组件都能够在值之间切换。问题是,当我单击其中一个时,另一个也会执行。我错过了设置这些的步骤吗?
父组件数据:
状态:

    constructor(props){
const userToggleSettings = {
cascadingPanels: true,
includeAttachments: true,
analyticsOptIn: false
};

this.state = {
userToggleSettings
};
}
切换功能:

toggleIncludeAttachments = () => {
this.setState((prevState) => (
{
userToggleSettings:
{
includeAttachments: !prevState.userToggleSettings.includeAttachments
}
}
));
};

toggleCascadingPanels = () => {
this.setState((prevState) => (
{
userToggleSettings:
{
cascadingPanels: !prevState.userToggleSettings.cascadingPanels
}
}
));
};

includeAttachmentsClickHandler = () => {
this.toggleIncludeAttachments();
}

cascadingPanelsClickHandler = () => {
this.toggleCascadingPanels();
}

将值和函数作为 Prop 传递:
<ChildComponent
attachmentsSwitchHandler={this.toggleIncludeAttachments}
attachmentsSwitchValue={this.state.userToggleSettings.includeAttachments}
cascadingPanelsSwitchHandler={this.toggleCascadingPanels}
cascadingPanelsSwitchValue={this.state.userToggleSettings.cascadingPanels}
/>

子组件数据
在子组件中设置点击事件和值:
<div className='child-component-container'>
<div className={'user-settings-toggle'}
onClick={props.cascadingPanelsSwitchHandler}
>
<div className={'user-settings-label'}>
{props.translations.CASCADING_PANELS}
</div>
<Switch
checked={props.cascadingPanelsSwitchValue}
translations={{
off: props.translations.off,
on: props.translations.ON
}}
/>
</div>
<div className={'user-settings-toggle'}
onClick={props.attachmentsSwitchHandler}
>
<Switch
checked={props.attachmentsSwitchValue}
translations={{
off: props.translations.off,
on: props.translations.ON
}}
/>
<div className={'user-settings-label'}>
{props.translations.ALWAYS_INCLUDE_ATTACHMENTS}
</div>
</div>
演示:
enter image description here
有人可以澄清我在这里做错了什么吗?

最佳答案

您应该以这种方式更改切换功能:

 this.setState((prevState) => (
{
userToggleSettings:
{
...prevState.userToggleSettings, // ---> added
cascadingPanels: !prevState.userToggleSettings.cascadingPanels
}
}
));
React 不执行“深度合并”,即嵌套对象不合并。仅合并顶级属性。
因此,您拥有它的方式会丢失 userToggleSettings 中的所有内容。对象,在做 setState 之后.

关于javascript - 为什么我的 React 应用程序中的两个点击事件会同时运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69576288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com