首页 文章

是否可以在React Native中调用父组件中的函数?

提问于
浏览
6

我对React Native仍然很陌生,我认为这个问题是对React的一个基本误解 .

我正试图通过按NavigationBar按钮打开一个模态 . 自定义组件I 'm using ( 878709 ) and the React Native Modal use child components to trigger the event. I can' t都知道如何通过按下右侧按钮来打开模态 .

<ModalPicker 
    data = {[
        {key: '1', label: '1'},
        {key: '2', label: '2'},
        {key: '3', label: '3'}
    ]}
    initValue = 'Select option'
    selectStyle={{
        height: 200
    }}>
    <NavigationBar
        title={{ title: "ModalTest" }}
        rightButton={{ title: "Open Modal"
        handler: () => ModalPicker.open() }}
    />
 </ModalPicker>

我正在尝试确定是否可以从NavigationBar组件的“rightButton”prop调用open(),一个ModalPicker组件的函数 .

ModalPicker的组件确实有一个打开的功能,当我将一个TouchableHighlight作为一个孩子时它可以工作,但是如何在子组件道具中调用该函数?

这是应用程序的主要组成部分 .

1 回答

  • 0

    您可以将 ref='picker' 用作父组件,并通过 this.refs.picker 引用它

    <ModalPicker
        data = {[
            {key: '1', label: '1'},
            {key: '2', label: '2'},
            {key: '3', label: '3'}
        ]}
        ref='picker'
        initValue = 'Select option'
        selectStyle={{
            height: 200
        }}>
        <NavigationBar
            title={{ title: "ModalTest" }}
            rightButton={{ title: "Open Modal",
            handler: () => this.refs.picker.open() }}
        />
     </ModalPicker>
    

相关问题