【问题标题】:Ref to child component引用子组件
【发布时间】:2019-04-23 01:21:40
【问题描述】:

我无法使用 ref 访问孩子的功能。 如果我尝试检查this.child.current,则会列出孩子的props

class BottomPanel extends React.Component<Props, {}> {
  constructor(props) {
    super(props);
    this.child = React.createRef();
    this.onClick = this.onClick.bind(this);
  }

  onClick() {
    this.child.current.getAlert();
  }

  render() {
    <div>
      <BottomPanelPeriodList ref={this.child}>
        <div label={<FormattedMessage id="bottomPanel.threeMonth" />} />
        <div label={<FormattedMessage id="bottomPanel.sixMonth" />} />
      </BottomPanelPeriodList>
    </div>
  }
}
export default connect(mapStateToProps)(BottomPanel);

class BottomPanelPeriodList extends React.Component<Props, State> {
  getAlert = () => {
    alert('HELLOWORLD!');
  };

  render() {
    ...
  }
}
export default connect(null, mapDispatchToProps, null, { forwardRef: true })(BottomPanelPeriodList);

【问题讨论】:

  • 渲染后先用return()修正你的父组件

标签: reactjs ref


【解决方案1】:
render() {
 retuun(  <div>
  <BottomPanelPeriodList ref={this.child}>
    <div label={<FormattedMessage id="bottomPanel.threeMonth" />} />
    <div label={<FormattedMessage id="bottomPanel.sixMonth" />} />
  </BottomPanelPeriodList>
</div>)
}

进行更改并参考此链接 https://repl.it/@KishanJaiswal/HungryAustereRelationalmodel

【讨论】:

    猜你喜欢
    • 2021-08-15
    • 1970-01-01
    • 2019-08-10
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多