【问题标题】:Invoke nested child method using refs reactJS WithStyles [duplicate]使用refs reactJS WithStyles调用嵌套子方法[重复]
【发布时间】:2019-11-08 09:47:02
【问题描述】:

我正在尝试使用 refs 访问嵌套的 chilld 组件中的方法。这是为了删除嵌套删除组件中的数据。我的代码如下(简化代码):

父类:

class Parent extends Component {
  constructor(props) {
    this.childref = React.createRef()
    props.refs(this)
  }
  render() {
    const elements = return [
     <div onclick={this.callsupprimer(0)} />,
     <div onclick={this.callsupprimer(1)} />
    ]
    return (
      <Fragment>
        <Child refs={ref => this.childref = ref>
        </Child>
       loadToolData()
     </Fragment>
     )
  }
  callsupprimer = index => this.childRef.GrandChildRef.supprimer(index)
}
 export withStyles(styles)(Parent)

儿童班:

class Child extends Component {
  constructor(props) {
    this.grandchildref = React.createRef()
    props.refs(this)
  }

  render() {
    return (
      <GrandChild refs={ref => this.grandchildref = ref>
      </GrandChild>
    )
  }
}
 export withStyles(styles)(Child)

孙子班:

class GrandChild extends Component {

  supprimer = (index) => {
        console.log(index)
        this.forceUpdate()
  }
  render() {
    return (
      //blah blah blah
    )
  }
}
export withStyles(styles)(GrandChild)

但是,我无法让 supprimer 方法在 GrandChild 的 this 上下文中调用更改。该方法被调用,但是以一种奇怪的方式。

它在组件加载并打印索引时被调用一次,但它不能在 onlick 上工作!!! 我什至没有在 grandChild 类中调用这个方法。请帮忙。

更新:代码与现在写的完全一样,只是方法名称不同。

【问题讨论】:

  • 不应该 componentDidUPdate(= 是 componentDidUpdate() 吗?:P
  • ^^ 谢谢,已更正,但这不是问题,我只是在这里手写了这段代码,以解释这个想法
  • 你需要用这个props.ref(this)调用GrandChild构造函数中的ref函数,然后你就可以使用childref从父级访问GrandChild
  • react 告诉我:TypeError: props.ref is not a function
  • 尝试通过this.childref insted of ref =&gt; this.childref = ref

标签: javascript reactjs react-with-styles


【解决方案1】:

问题是我在渲染时调用了callsupprimer,而它本应该只完成onClick,所以在渲染时调用了一次该方法,之后它就不起作用了。 一旦我将父类中的onClick 更改为箭头函数回调:

<div onclick={() => this.callsupprimer(1)} />

它按预期工作。

注意:在使用withstyles时,需要使用refs,而不是ref,然后像问题中那样在子组件中绑定this。我不需要使用current。 @Hai Alaluf 的问题中的 cmets 以正确的方式指出了我!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2017-06-03
    相关资源
    最近更新 更多