簡體   English   中英

將類組件轉換為功能組件 react native

[英]convert class components to functional components react native

因為我是 React Native 的新手。 我對類組件知之甚少。 我被困在代碼中,因為在這段代碼中使用了類組件,但我想將它們轉換為功能組件。 任何人都請幫助我將此給定代碼轉換為功能組件。 這是一個可刷卡的代碼,反應原生類組件中的所有給定代碼以及構造函數的使用和 this。 我只想將其轉換為功能組件。

    //This is an example of Tinder like Swipeable Card//
    import React, { Component } from 'react';
    //import react in our code.
    import {
    Platform, StyleSheet, View, Text,
    Dimensions, Animated, PanResponder,
    } from 'react-native';
    //import all the components we are going to use.
    const SCREEN_WIDTH = Dimensions.get('window').width;
    class SwipeableCard extends React.Component {
    constructor() {
    super();
    this.panResponder;
    this.state = {
        Xposition: new Animated.Value(0),
        RightText: false,
        LeftText: false,
    };
    this.Card_Opacity = new Animated.Value(1);

    this.panResponder = PanResponder.create({
        onStartShouldSetPanResponder: (evt, gestureState) => false,
        onMoveShouldSetPanResponder: (evt, gestureState) => true,
        onStartShouldSetPanResponderCapture: (evt, gestureState) => false,
        onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
        onPanResponderMove: (evt, gestureState) => {
            this.state.Xposition.setValue(gestureState.dx);
            if (gestureState.dx > SCREEN_WIDTH - 250) {
                this.setState({
                    RightText: true,
                    LeftText: false,
                });
            } else if (gestureState.dx < -SCREEN_WIDTH + 250) {
                this.setState({
                    LeftText: true,
                    RightText: false,
                });
            }
        },
        onPanResponderRelease: (evt, gestureState) => {
            if (
                gestureState.dx < SCREEN_WIDTH - 150 &&
                gestureState.dx > -SCREEN_WIDTH + 150
            ) {
                this.setState({
                    LeftText: false,
                    RightText: false,
                });
                Animated.spring(
                    this.state.Xposition,
                    {
                        toValue: 0,
                        speed: 5,
                        bounciness: 10,
                    },
                    { useNativeDriver: true }
                ).start();
            } else if (gestureState.dx > SCREEN_WIDTH - 150) {
                Animated.parallel(
                    [
                        Animated.timing(this.state.Xposition, {
                            toValue: SCREEN_WIDTH,
                            duration: 200,
                        }),
                        Animated.timing(this.Card_Opacity, {
                            toValue: 0,
                            duration: 200,
                        }),
                    ],
                    { useNativeDriver: true }
                ).start(() => {
                    this.setState({ LeftText: false, RightText: false }, () => {
                        this.props.removeCard();
                    });
                });
            } else if (gestureState.dx < -SCREEN_WIDTH + 150) {
                Animated.parallel(
                    [
                        Animated.timing(this.state.Xposition, {
                            toValue: -SCREEN_WIDTH,
                            duration: 200,
                        }),
                        Animated.timing(this.Card_Opacity, {
                            toValue: 0,
                            duration: 200,
                        }),
                    ],
                    { useNativeDriver: true }
                ).start(() => {
                    this.setState({ LeftText: false, RightText: false }, () => {
                        this.props.removeCard();
                    });
                });
            }
        },
    });
}
render() {
    const rotateCard = this.state.Xposition.interpolate({
        inputRange: [-200, 0, 200],
        outputRange: ['-20deg', '0deg', '20deg'],
    });
    return (
        <Animated.View
            {...this.panResponder.panHandlers}
            style={[
                styles.card_Style,
                {
                    backgroundColor: this.props.item.backgroundColor,
                    opacity: this.Card_Opacity,
                    transform: [
                        { translateX: this.state.Xposition },
                        { rotate: rotateCard },
                    ],
                },
            ]}>
            <Text style={styles.Card_Title}> {this.props.item.card_Title} </Text>
            {this.state.LeftText ? (
                <Text style={styles.Left_Text_Style}> Left Swipe </Text>
            ) : null}
            {this.state.RightText ? (
                <Text style={styles.Right_Text_Style}> Right Swipe </Text>
            ) : null}
        </Animated.View>
         );
     }
   }

    export default class App extends React.Component {
    constructor() {
    super();
    this.state = {
        Sample_Card_Array: [{
            id: '1', card_Title: 'Card 1', backgroundColor: '#FFC107',
        }, {
            id: '2', card_Title: 'Card 2', backgroundColor: '#ED2525',
        }, {
            id: '3', card_Title: 'Card 3', backgroundColor: '#E7088E',
        }, {
            id: '4', card_Title: 'Card 4', backgroundColor: '#00BCD4',
        }, {
            id: '5', card_Title: 'Card 5', backgroundColor: '#FFFB14',
        }],
        No_More_Card: false,
    };
}
componentDidMount() {
    this.setState({
        Sample_Card_Array: this.state.Sample_Card_Array.reverse(),
    });
    if (this.state.Sample_Card_Array.length == 0) {
        this.setState({ No_More_Card: true });
    }
}
removeCard = id => {
    this.state.Sample_Card_Array.splice(
        this.state.Sample_Card_Array.findIndex(x => x.id == id),
        1
    );
    this.setState({ Sample_Card_Array: this.state.Sample_Card_Array }, () => {
        if (this.state.Sample_Card_Array.length == 0) {
            this.setState({ No_More_Card: true });
        }
    });
};
render() {
    return (
        <View style={styles.MainContainer}>
            {this.state.Sample_Card_Array.map((item, key) => (
                <SwipeableCard
                    key={key}
                    item={item}
                    removeCard={this.removeCard.bind(this, item.id)}
                />
            ))}
            {this.state.No_More_Card ? (
                <Text style={{ fontSize: 22, color: '#000' }}>No Cards Found.</Text>
            ) : null}
        </View>
      );
     }
    }
    const styles = StyleSheet.create({
    MainContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: Platform.OS === 'ios' ? 20 : 0,
    },
    card_Style: {
    width: '75%',
    height: '45%',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    borderRadius: 7,
    },
    Card_Title: {
    color: '#fff',
    fontSize: 24,
    },
    Left_Text_Style: {
    top: 22,
    right: 32,
    position: 'absolute',
    color: '#fff',
    fontSize: 20,
    fontWeight: 'bold',
    backgroundColor: 'transparent',
    },
    Right_Text_Style: {
    top: 22,
    left: 32,
    position: 'absolute',
    color: '#fff',
    fontSize: 20,
    fontWeight: 'bold',
    backgroundColor: 'transparent',
    },
    });

render 方法中的部分是您返回的內容。

要在功能組件中創建 stateObjects,您需要使用useState方法

const functionalComponent = (props)=>{//props are passed in via props arg...
    const defaultState = Xposition: new Animated.Value(0),
        RightText: false,
        LeftText: false
    }
    const [state,setState] = useState(defaultState);
    ... // more stuff
    return (
        <Animated.View
            {...this.panResponder.panHandlers}
            style={[
                styles.card_Style,
                {
                    backgroundColor: props.item.backgroundColor,
                    opacity: Card_Opacity,
                    transform: [
                        { translateX: state.Xposition },
                        { rotate: rotateCard },
                    ],
                },
            ]}>
            <Text style={styles.Card_Title}> {props.item.card_Title} </Text>
            {this.state.LeftText ? (
                <Text style={styles.Left_Text_Style}> Left Swipe </Text>
            ) : null}
            {this.state.RightText ? (
                <Text style={styles.Right_Text_Style}> Right Swipe </Text>
            ) : null}
        </Animated.View>
         );
}

你真的應該去看一些關於 useState 的視頻,你可以更細化

要設置狀態,您將需要使用從useState調用返回的setState方法: setState({..state,{XPosition:55})或其他東西……您執行...state以包含舊狀態值,因為狀態變量將被您傳入的確切內容覆蓋......它不會“更新”現有狀態它會覆蓋它

下一點是掛鈎componentDidMount的功能,您可以使用useEffect做到這useEffect

useEffect(()=>{ // this is setup
    // do the stuff from componentDidMount
    return ()=>{ 
       // any required teardown can be done here
    },[] //[] signifies only do this when component mounts... not every update 
);// end useEffect componentDidMount

如果你想在特定狀態或道具更新時做一些事情,還有更多 useEffect 可以使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM