首页 > 解决方案 > OnChange 处理程序仅在组件的第一个实例中触发,即使它是在不同实例上触发的

问题描述

我有一个组件,它本质上是一个菜单项列表,每个菜单项都有一个独特的形式。

我需要在 HTML 页面和 Modal 两个实例中呈现这个组件。

在 HTML 页面已经呈现并且我打开模式并在菜单项上执行操作的情况下,onChange 处理程序仅在 HTML 页面中而不是在模式中被触发,即使该操作是在模态的。

这是我的组件

class MyComp extends Component {

 toggleHandler(){
   const {owner} = this.props;
   //perform an action
   console.log("owner is : ", owner)
 }

 render(){
   return(
      <div class="checkbox_style">
         <input
            type="checkbox"
            id="checkbox"
            onClick={this.toggleHandler}
          />
      </div>
  );
 }

}


我在两种情况下使用它


class ContentComp extends Component{
 render(){
    {this.renderOtherComps}
    <MyComp {...this.props} owner="home" />

 }
}

class HeaderComp extends Component{
 render(){
    {this.renderOtherComps}
    <Modalbutton //launches ModalComp />    
 }
}

class ModalComp extends Comp{
   render(){
     //Using some common modal details
     <MyComp {...this.props} owner="modal" />
   }
}

class HomeComp extends Component{
 render(){
    {this.renderHeaderComp}
    <MyComp {...this.props} owner="home" />
    {this.renderFooterComp}
 }
}

ModalButton 被触发 ModalComp 与 MyComp 一起加载。

触发 MyComp 和 console.log 中的复选框

-> 主人在家

预期输出为

-> 所有者是模态的

因此,重新渲染在 ModalComp 中不起作用。

我已经使用了 shouldComponentUpdate 并尝试设置标志以在打开模式时返回 false。不会停止这种行为

标签: javascriptreactjsevent-handlingdom-events

解决方案


推荐阅读