将onClick从孩子传递给父母

时间:2020-06-30 19:01:42

标签: reactjs gatsby

我有组件foo.js,带有带有2个按钮的卡堆(打开和关闭模式),但与此同时,我想将事件传递给父级bar.js

我的动机是在事件发生时更改父类,在这种情况下,我希望当单击打开按钮并使关闭按钮恢复正常时,外部包装为overflow hidden


// foo.js

import React from 'react'

class GridWithModal extends React.Component {
  constructor(props) {
        super(props);
        this.state = {
            lecturerList: this.props.lecturers,
            lectorIndex: null,
            isModalOpen: false
        };
        this.showModal = this.showModal.bind(this);
    }

    showModal(id) {
        this.setState({
            lectorIndex: id,
            isModalOpen: true
        });
    }
   
   render() {
     const { lecturerList, lectorIndex, Content } = this.state;
     
     return (
        <>
          {lecturerList.map((lector, index) => {
              return (
                 // my card stuff here...
                 <button
                     onClick={e => {
                          this.showModal(index); // this open the modal 
                     }}>
                      Open The Modal
                 </button>
              )
          })}

           
          <div className="modal">
             // modal stuff here
             <button
             onClick={e => this.setState({ dosenIndex: null })}> // this close the modal
             Close Modal
             </button>
          </div>
          
        </>
     )
   }

}

export default GridWithModal

// bar.js
import React from 'react'

const Layout = ({children}) => {
  
  return (
      <div className="bar"> // this is the element that i want to pass the event to add and remove class when the event occured
         <main> 
             {children} // foo.js somewhere inside this chilldren
        </main>
      </div>
  )

}

export default Layout

2 个答案:

答案 0 :(得分:1)

在父组件show/hide中创建bar.js方法,并将这些方法传递给子组件。

点击操作后,只需从子组件中调用这些方法,就可以解决问题。

答案 1 :(得分:0)

您的bar.js应该将一个属性传递给foo.js,然后在您的onClick中,您应该调用传递回prop的{​​{1}}函数。

回答此问题:

@FerranBuireu感谢您的参考,我读了但仍然迷路 关于如何将bar.js放在我的两个按钮中的原因 已经有功能了

在这种情况下,您应该在{props.handleThisClick}中使用同时管理这两个功能的功能。改变这个:

foo.js

对此:

 <button onClick={e => this.showModal(index)}>

然后,您的<button onClick={e => this.handleStuff(index)}> 函数应为:

handleStuff

handleStuff(id){ showModal(id) props.handleModal(modalState) // change modalState for your value or state } showModal(id) { this.setState({ lectorIndex: id, isModalOpen: true }); } 中,当在子组件内部执行bar.js时,将触发功能handleModal