【问题标题】:React use refs from parent to child反应使用从父母到孩子的参考
【发布时间】:2018-10-05 11:48:12
【问题描述】:

我在 react.js 中将 jqwidget 用于网格。我有 JqxListBox 在我的父组件中有一个选项列表。

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return <JqxListBox ref='myListBox' style={{ float: 'left' }} width={150} height={150} source={listBoxSource} checkboxes={true} />;
  }
}

当用户在 jqxlistbox 中选择或取消选择某个选项时,我想在网格中打开显示和隐藏列,但在子组件中无法访问参考。如何在子组件 react 中访问 jqxlistbox 属性。在子 componentDidMount 函数中,我正在访问 ref 之类的。

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    // Cannot read property 'on' of undefined
    this.refs.myListBox.on('checkChange', (event) => {
      console.log("something");
    });
  }

  render() {
    return <div>Child component</div>;
  }
}

它给了我错误:TypeError: Cannot read property 'on' of undefined

【问题讨论】:

  • 你使用的是哪个版本的 React ?
  • @klugjo 我正在使用 react 16.3.2。
  • 父子组件之间没有关系

标签: javascript reactjs jqwidget


【解决方案1】:

他们访问refs 的方式在 React 16.3.2 中发生了变化:

这是您应该设置的方式:

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    // Declare and initialize the ref in the constructor
    this.myListBox= React.createRef();
  }

  componentDidMount() {
    // Access the ref
    this.myListBox.on('checkChange', (event) => {
      this.props.onEventFromParentComponent(event);
    });
  }

  render() {
    return <JqxListBox ref={this.myListBox} style={{ float: 'left' }} width={150} height={150} source={listBoxSource} checkboxes={true} />;
  }
}

【讨论】:

  • 这个例子是针对同一个组件,但我想在我的子组件中访问 this.myListBox.on。
  • 不要那样做。使用 ref 已经是一个糟糕的模式,你只会让它变得更糟。冒泡事件 -> 我已更新代码以反映这一点
  • 我有一个基于我在子组件中重新加载网格的表单,所以在父组件中我有 jqxlistbox,其中用户选择列列表并基于此我需要重新加载子组件。请参阅ibb.co/fqwXeH
  • 他们不是父子,只是两个不同的组件。基本上你的列表框的引用需要在同一个类中,否则它不起作用
  • 我可以在父级中传递参考,就像在子级中一样。
猜你喜欢
  • 1970-01-01
  • 2018-07-07
  • 2020-01-09
  • 2021-10-03
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
相关资源
最近更新 更多