Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - Child cannot trigger function that belongs to the parent in Reactjs

I have a modal parent component and a form child component. The function that opens and closes the modal is in the parent, but the submit function is in the child. What I want to do is to close the modal on submit, but for that I need the submit function from the child to trigger the close modal function from the parent. I know how to pass a function from < Parent /> to < Child />, but in here the difference is that the child is returned in the parent in this form {children}. How can I do this when the child is returned in this form ?

This is the modal component or the parent:

<ModalInMobile
      id="SearchFiltersMobile.filters"
      isModalOpenOnMobile={this.state.isFiltersOpenOnMobile}
      onClose={this.cancelFilters}
      showAsModalMaxWidth={showAsModalMaxWidth}
      onManageDisableScrolling={onManageDisableScrolling}
      containerClassName={modalContainerStyles}
      closeButtonMessage={modalCloseButtonMessage}
    >
      <button className={showListingsButtonStyles} onClick={this.closeFilters}>
      X
        </button>
      {this.state.isFiltersOpenOnMobile ? (
        <div className={modalFilterWrapperStyles}>{children[this.state.renderingModals]}</div>
      ) : null} 
    </ModalInMobile>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use cloneElement to pass your props to your children.

export default function App() {
  return (
    <div className="App">
      <Parent>
          <Child />
      </Parent>
    </div>
  );
}



const Child = ({ parentProps }) => {


  return (<div>I am a child ({parentProps})</div>)

}

const Parent = ({ children }) => {

  const iAmProps = "i am a prop"

  const childProps = React.Children.map(children, child => {

    if (React.isValidElement(child)) {
      return React.cloneElement(child, { parentProps: iAmProps }); //add your props here.
    }
    return child;
  });

  return ( <>{childProps}</>)

}

codesandbox


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...