通过参考

时间:2017-09-08 16:32:20

标签: reactjs redux react-redux

我有一个简单的组件,它公开了一个名为doIt的方法,但是这个组件包含在redux connect中,因此我无法访问它。这是我的简单组件:

class LoginSwitchDumb extends Component {
    render() { ... }
    doIt = (value: boolean) => alert('hi')
}

const LoginSwitch = connect(...)(LoginSwitchDumb)

export LoginSwitch

我在父母身上渲染这个元素:

render() {
    return (
        <View>
            <LoginSwitch id={id} kind={kind} ref={this.refSwitch} />
        </View>
    )
}

refSwitch = el => {
    console.log('reffing switch:', Object.keys(el));
}

但是我们在控制台登录refSwitch上看到,它不允许我访问doIt。如果我没有将它包装在connect我可以访问它,那么这就是未用connect包裹时记录的内容:

  

数组[“props”,“context”,“refs”,“updater”,“doIt”,“_ lastInternalInstance”,“state”]

我们在这里看到了doIt,但是当我用connect包裹它时,它不在那里,我们看到了这一点:

  

Array [“props”,“context”,“refs”,“updater”,“version”,“state”,“renderCount”,“store”,“propsMode”,“setWrappedInstance”,“selector”,“订阅“,”notifyNestedSubs“,”_ reactInternalInstance“]

无论如何都要点击这个来到doIt

1 个答案:

答案 0 :(得分:2)

您可以在包装的组件上调用getWrappedInstance以获取底层组件实例。为此,您还需要将选项中的{ withRef: true }传递给connect

const LoginSwitch = connect(..., ..., ..., { withRef: true })(LoginSwitchDumb)

并在父母:

refSwitch = el => {
  console.log('reffing switch:', Object.keys(el.getWrappedInstance()));
}