当组件是被connect绑定redux后,可以使用getWrappedInstance()获取组件的原型,但需要给connect添加{ withRef: true }选项才能使用
- connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
其中mergeProps(stateProps, dispatchProps, ownProps)是用于特定情况下,修改提供给组件的props
1 2 3 4
| function mergeProps(stateProps, dispatchProps, ownProps) { //默认情况下返回 return Object.assign({}, ownProps, stateProps, dispatchProps) }
|
需要添加的{ withRef: true }选项要放在connect的第四个参数
###example
使用connect绑定redux的后test组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import {connect} from 'react-redux' import {Component} from 'react' export default class Test extends Component { constructor(props) { super(props); } testFunction =(test='1')=>{ alert(test) } render() { return ( <div>test</div> ) } } function mergeProps(stateProps, dispatchProps, ownProps) { return Object.assign({}, ownProps, stateProps, dispatchProps) } export default connect({}, {},mergeProps,{withRef:true})(Test)
|
获取test组件的原型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import {Component} from 'react' import Test from './Test' export default class Test2 extends Component { constructor(props) { super(props); } componentWillMount(){ this.refs.test.getWrappedInstance().testFunction('test') } render() { return ( <div><Test ref='test' /></div> ) } }
|