【发布时间】: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.childrefinsted ofref => this.childref = ref
标签: javascript reactjs react-with-styles