connect(mapStateToProps, mapDispatchToProsp, null, { withRef: true })
// child comp
class Child extends React.Component {
focus() {
this.refs.input.focus()
}
render () {
return (
<div><input type="text" ref="input" /></div>
)
}
}
// connect的options参数withRef必须设置为true
export default connect(mapStateToProps, mapDispatchToProsp, null, { withRef: true })(Child)
// parent child
class Parent extends React.Component {
// 调用子组件的方法
callChildMethod () {
this.refs.child.getWrappedInstance().focus()
}
render () { ... }
}
还有种更加优雅的方法,如下:
本文介绍了如何在React中通过设置withRef为true来访问被高阶组件包裹的子组件实例,并提供了一种更优雅的方法。
8902

被折叠的 条评论
为什么被折叠?



