如何将多个函数从类组件传递到功能组件

时间:2018-02-15 05:01:27

标签: reactjs react-native react-native-android

我有新的反应,我的目标是从类组件传递一个函数,在单击按钮时在类组件内执行。代码细分如下。

类组件类如下所示

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Dimensions,
  Text,
  View
} from 'react-native';
import Header from './src/components/Header';
import { Drawer } from 'native-base';

export default class App extends Component {
  closeDrawer=()=> {
   this._drawer._root.close()
  };
 openDrawer=()=> {
   this._drawer._root.open()
 };


  render() {
    return (
      <Drawer
        openDrawerOffset={100}
        styles={drawerStyles}
        ref={(ref) => { this._drawer = ref; }}
        content={<SideBar navigator={this._navigator} />}
        onClose={() => this.closeDrawer()} >
        <View style={{ flex: 1 }} >

          <View>
            <Header openDrawerClicked={this.openDrawer} />
          </View>

        </View>
      </Drawer>
    );
  }
}

我需要传递&#34; openDrawer&#34;首先执行Header组件,然后在内部我有一个按钮配置在一个单独的子组件中,其中按钮单击被配置。编码如下:

标题组件

const Header = (props) => {

    return (

                <View style={styles.menuViewStyle}>
                    <Button imagePath={'menuIcon'}/>
                </View>
    );
};

按钮组件,我需要执行该功能并切换打开和关闭功能。

const assets = require('./assets')

const ButtonWithImage = (props) => {
    const { buttonStyle } = styles;
    const clickEvent = () => {
        // Button click event
    }

    return (
        <TouchableOpacity onPress={clickEvent} style={buttonStyle}>
            <Image
                source={assets[props.imagePath]}
                style={styles.ImageIconStyle}
            />
        </TouchableOpacity>
    );
};

2 个答案:

答案 0 :(得分:3)

export default class App extends Component {
  openDrawer=()=> { //bind lexical scope using arrow synax
    this._drawer._root.open()
  };

  render() {
    return (
      //....
          <View>
            <Header openDrawerClicked={this.openDrawer} />
          </View>
    );
  }
}

在标题中:

const Header = ({openDrawerClicked}) => {  // get `openDrawerClicked`

    return (
   //passed `openDrawerClicked` for Button component
                <View style={styles.menuViewStyle}>
                    <Button openDrawer= {openDrawerClicked} imagePath={'menuIcon'}/>
                </View>
    );
};

按钮:

const ButtonWithImage = (props) => {
    const clickEvent = () => {
        props.openDrawer();
    }

    return (
        <TouchableOpacity onPress={props.clickEvent} style={buttonStyle}>
            //...
        </TouchableOpacity>
    );
};

答案 1 :(得分:1)

首先,您需要将函数从Header组件传递给Button组件,如下所示:

<Button imagePath={'menuIcon'} openDrawerClicked={props.openDrawerClicked} />

然后在按钮组件内部调用该方法,如下所示:

const clickEvent = () => {
    props.openDrawerClicked();
}

建议:

为了避免混淆,可以在openDrawerClickedopenDrawer的所有地方使用相同的名称,否则在父组件中,函数名称将为openDrawer,而子名称将为{{ 1}}。