簡體   English   中英

無法使用父 class 組件和子功能組件打開/關閉模態

[英]Unable to open/close modal with parent class component and child functional component

我有一個父組件,我正在努力正確打開/關閉子組件(模態)。 下面的兩個代碼框是我的組件的簡化示例。

編輯:這是一個帶有以下代碼的代碼沙箱——沒有實際的模式,但是我已經記錄了我認為會對這個問題產生影響的所有有狀態值,你可以看到它們是如何改變/改變的不要像我希望的那樣改變。

代碼沙箱

  • 當父組件打開時,我可以單擊 MenuItem 並且可以看到 state 更改,但是除非我暫時關閉父組件並重新打開它,否則模態不會打開(然后父組件打開時模態已經打開)
  • When the modal is open, and I try to close by clicking the close button (which has the state changing function from parent inside of the onClick method. this.state.showModal remains true, and doesn't change to false.
  • 如果我向子組件添加一個 closeModal 狀態值並在關閉按鈕 onClick 期間更改它,this.state.showModal 仍然是 true。

感謝任何伸出援手的人,如果您有任何澄清問題,請隨時提出!

class Parent extends Component {
    
    constructor(props) {
      super(props);
      this.showModal = this.showModal.bind(this);
      this.closeModal = this.closeModal.bind(this)
      this.state = {
        showModal: false
      };
    this.showModal = this.showModal.bind(this)
    this.closeModal = this.closeModal.bind(this)
    }
    showModal() {
      this.setState({ showModal: true });
    }
    closeModal() {
      this.setState({ showModal: false });
    }
    render() { 
      return (
      <MenuItem onClick={this.showModal}>
      <ChildComponent
       prop1={prop1}
       isOpen={this.state.showModal}
       closeModal={this.closeModal}
       />
       </MenuItem>
)}
const ChildComponent = ({
  prop1,
  isOpen,
  closeModal
  }) => {
  
  const [modalOpen, setModalOpen] = useState(isOpen)


  useEffect(() => {
    setModalOpen(isOpen)
  },[isOpen])
  
  console.log('isopen on child', isOpen)
  console.log('modalOpen', modalOpen)
  return (
  <div>
   {modalOpen && (
  <button
  onClick={() => {
    setModalOpen(false)
    closeModal()
  }}
  >
    {'click to close modal'}
    </button>
   )}
   </div>
)}

)}

我發現了我的問題!

在我的父組件中,設置模態打開的 onClick 處理程序包裝了我的子組件。 我需要刪除它並有條件地單獨渲染它,如下所示:

<div>
        <div onClick={this.showModal}>{"Click here to open modal"}</div>
        {this.state.showModal && (
          <ChildComponent
            prop1={prop1}
            isOpen={this.state.showModal}
            closeModal={this.closeModal}
          />
        )}
      </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM