如何用一个反应组件来触发两个功能?

时间:2019-03-29 06:01:24

标签: react-native

我为通用按钮创建了带有动画的类组件:

import React, { Component } from 'react';
import { Text, TouchableOpacity, StyleSheet, Animated, Easing, View } from 'react-native';

class AnimatedPrimaryButton extends Component {
  constructor(props) {
    super(props);

    this.state = {
      toggle: false,
      animated: new Animated.Value(0)
    }
  }

  animatedButton = (toggle) => {
    this.state.animated.setValue(toggle ? 1 : 0);

    Animated.timing(this.state.animated, {
      toValue: toggle ? 0 : 1,
      duration: 250,
      easing: Easing.bounce
    }).start();

    this.setState({ toggle: !toggle });
  }

  render() {
    const { toggle, animated } = this.state;
    const { onPress, disabled, width, height } = this.props;

    return (
      <TouchableOpacity
        disabled={disabled} 
        onPress={onPress} 
        style={[styles.buttonStyle, { width, height }]}
      >
        <Animated.View style={{ 
            // other styles
            transform: [{ scale: animated.interpolate({ inputRange: [0, 1], outputRange: [0, 1]})
              }
            ]
        }}>
        </Animated.View>
        <Text style={[styles.textStyle, { fontSize }]}>
          {children}
        </Text>
      </TouchableOpacity>
    );
  }; 
}

const styles = StyleSheet.create({
  // some styles
});

export default AnimatedPrimaryButton;

我在其他屏幕上使用创建组件,例如:

import AnimatedPrimaryButton from '../Shared/Button/AnimatedPrimaryButton';

doSomething = () => {
  // do something...
}

render() {
  return (
    <View>
      <AnimatedPrimaryButton
        onPress={() => this.doSomething()}
        width={400} 
        height={57} 
        fontSize={20} 
        backgroundColor={confirmButtonBg}
        disabled={disabledConfirmButton}
      >
        {I18n.t('SIGN_IN_BUTTON')}
      </AnimatedPrimaryButton>
    </View>
  );
}

现在,我想使用doSomething函数并同时触发animatedButton

在某些情况下,我的disable将切换为true或false,因此我尝试将AnimatedPrimaryButton上的代码设置为无效。

onPress={() => !disabled ? this.animatedButton(toggle) : onPress} 

使用箭头功能下的道具onPress似乎无效。

如何在类组件doSomething上使用animatedButtonAnimatedPrimaryButton函数?

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

AnimatedPrimaryButton组件中,您可以创建onPress函数

onPress(){
  this.props.onPress();
  this. animatedButton();
}

请注意,在其他屏幕上调用AnimatedPrimaryButton时,您可以在onPress上正确发送doSomething()函数。