繁体   English   中英

如何使用按钮从一个组件调用函数到另一个组件

[英]How to call function from one component to another component with Button

我在一个名为formSignup.js组件中创建了一个Submit()函数,并创建了另一个名为buttonSubmit.js组件,其中包含带有该按钮的 Button(onPress) 我想调用位于ormSignup.js Submit()函数。

为提交按钮创建单独组件的原因是,我为动画编写了很多代码,而且我想在loginComponent.js重用该按钮。

表单注册.js

submit = () => {
...
}

按钮提交.js

How can i call submit function from  fromSignup.js here

  _onPress() {
    if (this.state.isLoading ) return;

    this.setState({isLoading: true});
    Animated.timing(this.buttonAnimated, {
      toValue: 1,
      duration: 200,
      easing: Easing.linear,
    }).start();

    setTimeout(() => {
      this._onGrow();
    }, 2000);

    setTimeout(() => {
      Actions.mainScreen();
      this.setState({isLoading: false});
      this.buttonAnimated.setValue(0);
      this.growAnimated.setValue(0);
    }, 2300);

  }
-----
return(
          <TouchableOpacity
            onPress={this._onPress}
            activeOpacity={1}>
            {this.state.isLoading ? (
              <Image source={spinner} style={styles.image} />
            ) : (
              <Text style={styles.text}>Go</Text>
            )}
          </TouchableOpacity>
);

在你的情况下,我有一个疑问。

您是否在 formSignup.js 组件中使用 buttonSubmit.js 组件?

如果,您可以通过将函数作为 props传递来实现它。

//FormSignup.js
const FormSignup = () =>{
    const submit = () => {
        // some submit logic
    };

  //render
    return (
        <View>
            ....
            // if you are using the ButtonSubmit component in FormSignup.js, you 
            // can get function by props

            <ButtonSubmit onPressButton = {()=>submit()}/>
        </View>
    )
}


//ButtonSubmit.js
const ButtonSubmit = (props) => {
    return (
        <TouchableOpacity onPress={props.onPressButton}>
            <Text>submit</Text>
        </TouchableOpacity>
    )
}

如果,您应该单独编写该函数并将其导入到 ButtonSubmit.js 组件中

// Utility.js

const submit = () => {
    // submit logic
};

export {submit};

//================================//
//ButtonSubmit.js

import { submit } from './path/Utility.js'  // import the submit method

const ButtonSubmit = () => {
    return (
        <TouchableOpacity onPress={()=>submit()}>
            <Text>submit</Text>
        </TouchableOpacity>
    )
}

您可以将函数作为道具传递

<buttonSubmit onSubmit={this.submit} />

在你的 buttonSubmit.js 中,你可以在任何你想要的地方从 props 调用它。

//inside somewhere inside buttonSubmit you call:
this.props.onSubmit();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM