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 () { ... }
}
还有种更加优雅的方法,如下: