【问题标题】:Child cannot trigger function that belongs to the parent in Reactjs在 Reactjs 中,子级无法触发属于父级的函数
【发布时间】:2021-04-16 06:35:03
【问题描述】:

我有一个模态父组件和一个表单子组件。打开和关闭模态框的功能在父级中,但提交功能在子级中。我想要做的是在提交时关闭模态,但为此我需要 来自子项的提交函数 来触发 来自父项的关闭模态函数。我知道如何将一个函数从< Parent /> 传递给< Child />,但这里的区别在于,孩子以{children} 的这种形式返回到父级中。当孩子以这种形式返回时,我该怎么做?

这是模态组件或父组件:

<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>

【问题讨论】:

标签: javascript reactjs forms parent children


【解决方案1】:

您可以使用 cloneElement 将您的道具传递给您的孩子。

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

【讨论】:

  • 问题是我不能在父母中做你的第二步,因为孩子不是像 这样的组件形式,只是 {children}
  • 它不在您的问题代码中。为什么不显示需要调试的代码?如果你没有显示需要调试的正确代码,你就浪费了每个人的时间,在这种情况下,我的时间。
  • 他做到了——“但在这里不同的是,孩子在父母中以这种形式返回 {children}”
  • 添加了答案更新以将道具传递给 props.children
猜你喜欢
  • 2019-02-07
  • 2017-05-04
  • 1970-01-01
  • 2017-03-25
  • 2020-06-26
  • 2013-11-24
  • 2016-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多