(React Native) 如何 Class 发挥作用

(React Native) How to Class to Function

我的英语不是很好;我准备了一份申请。我想使用以下 class 结构作为 functionconst。我怎样才能做到这一点?我想使用函数组件使用props.

我添加了整个代码。 年龄计算应用

我用了useState-useEffect,没成功

等待帮助我谢谢你

import React from "react";
import {
  StyleSheet,
  Text,
  View,
  Dimensions,
  Platform,
  TouchableOpacity,
} from "react-native";
import DateTimePicker from "react-native-modal-datetime-picker";

const { height } = Dimensions.get("window");

export default class App extends React.Component {
  state = {
    isDateTimePickerVisible: false,
    date: undefined,
  };

  _showDateTimePicker = () => this.setState({ isDateTimePickerVisible: true });

  _hideDateTimePicker = () => this.setState({ isDateTimePickerVisible: false });

  _handleDatePicked = (date) => {
    date = new Date(date);
    this.setState({ date: date }, () => {
      this._hideDateTimePicker();
      this._calculateTheDifference();
    });
  };
  _calculateTheDifference() {
    if (!this.state.date) {
      return;
    }
    let current_date = new Date().getDate();
    let current_month = new Date().getMonth();
    let current_year = new Date().getFullYear();
    let birth_date = this.state.date.getDate();
    let birth_month = this.state.date.getMonth();
    let birth_year = this.state.date.getFullYear();
    let month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (birth_date > current_date) {
      current_month = current_month - 1;
      current_date = current_date + month[birth_month - 1];
    }
    if (birth_month > current_month) {
      current_year = current_year - 1;
      current_month = current_month + 12;
    }
    let calculated_date = current_date - birth_date;
    let calculated_month = current_month - birth_month;
    let calculated_year = current_year - birth_year;
    if (calculated_date || calculated_month || calculated_year)
      this.setState({
        calculated_date: calculated_date,
        calculated_month: calculated_month,
        calculated_year: calculated_year,
        dateOpacity: 1,
      });
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.slider}>
          <View style={{ justifyContent: "center", alignItems: "center" }}>
            <Text style={styles.yasHesaplama}>Age Calculate</Text>
          </View>
        </View>
        <View style={{ flex: 1, backgroundColor: "#fff" }}>
          <View style={styles.solKose} />
          <View
            style={{
              flex: 1,
              backgroundColor: "#fff",
              borderTopLeftRadius: 65,
            }}
          />
        </View>
        <View style={styles.anaGovde}>
          <TouchableOpacity
            style={styles.touchableOpacity}
            onPress={this._showDateTimePicker}
          >
            <Text style={styles.dogumGunu}>Enter your birthday.</Text>
          </TouchableOpacity>
          <View style={[styles.viewText, { padding: 10 }]}>
            <Text style={styles.text}>
              {this.state.calculated_year}
              {" Year"}{" "}
            </Text>
            <Text style={styles.text}>
              {this.state.calculated_month}
              {" Month"}{" "}
            </Text>
            <Text style={styles.text}>
              {this.state.calculated_date}
              {" Date"}{" "}
            </Text>
          </View>
        </View>
        <DateTimePicker
          isVisible={this.state.isDateTimePickerVisible}
          onConfirm={this._handleDatePicked}
          onCancel={this._hideDateTimePicker}
          mode={"date"}
          maximumDate={new Date()}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
  slider: {
    ...Platform.select({
      ios: {
        height: 0.3 * height,
        backgroundColor: "#C12699",
        borderBottomRightRadius: 65,
      },
      android: {
        height: 0.3 * height,
        backgroundColor: "#009A88",
        borderBottomRightRadius: 65,
      },
    }),
  },
  text: {
    paddingHorizontal: 5,
    justifyContent: "center",
    alignItems: "center",
    fontSize: 30,
    fontWeight: "bold",
    color: "#fff",
  },
  viewText: {
    ...Platform.select({
      ios: {
        height: 150,
        width: Dimensions.get("window").height / 2.6,
        flexDirection: "row",
        backgroundColor: "#C12699",
        justifyContent: "center",
        alignItems: "center",
        borderRadius: 10,
      },
      android: {
        height: 120,
        width: Dimensions.get("window").height / 2,
        flexDirection: "row",
        backgroundColor: "#009A88",
        justifyContent: "center",
        alignItems: "center",
        borderRadius: 10,
        top: 40,
      },
    }),
  },
  dogumGunu: {
    ...Platform.select({
      ios: {
        fontSize: 20,
        color: "#fff",
        fontWeight: "bold",
        borderWidth: 2,
        borderColor: "#fff",
        borderRadius: 10,
        padding: 20,
      },
      android: {
        fontSize: 20,
        color: "#fff",
        fontWeight: "bold",
        borderWidth: 2,
        borderColor: "#fff",
        borderRadius: 10,
        padding: 10,
      },
    }),
  },
  yasHesaplama: {
    ...Platform.select({
      ios: {
        top: 100,
        fontSize: 40,
        color: "#fff",
        fontWeight: "bold",
        borderWidth: 2,
        borderColor: "#fff",
        borderRadius: 10,
        padding: 20,
      },
      android: {
        top: 50,
        fontSize: 35,
        color: "#fff",
        fontWeight: "bold",
        borderWidth: 2,
        borderColor: "#fff",
        borderRadius: 10,
        padding: 10,
      },
    }),
  },
  touchableOpacity: {
    ...Platform.select({
      ios: {
        height: 100,
        width: Dimensions.get("window").height / 3,
        backgroundColor: "#C12699",
        alignItems: "center",
        justifyContent: "center",
        borderRadius: 10,
      },
      android: {
        height: 80,
        width: Dimensions.get("window").height / 2.3,
        backgroundColor: "#009A88",
        alignItems: "center",
        justifyContent: "center",
        borderRadius: 10,
      },
    }),
  },
  anaGovde: {
    ...Platform.select({
      ios: {
        flex: 1,
        justifyContent: "space-between",
        alignItems: "center",
        bottom: 210,
      },
      android: {
        flex: 1,
        justifyContent: "space-between",
        alignItems: "center",
        bottom: 150,
      },
    }),
  },
  solKose: {
    ...Platform.select({
      ios: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: "#C12699",
      },
      android: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: "#009A88",
      },
    }),
  },
});


看起来像这样

import React from 'react';
import { View, Text } from 'react-native';

import { connect } from 'react-redux';

export default function Rewards(props) {
  const [state, setState] = React.useState({
    isDateTimePickerVisible: false,
    date: undefined,
    millSecLeft: 0,
    dateOpacity: 1,
  });

  console.log(props); // Your props here

  const _showDateTimePicker = () =>
    setState({ ...state, isDateTimePickerVisible: true });

  const _hideDateTimePicker = () =>
    setState({ ...state, isDateTimePickerVisible: false });

  const _handleDatePicked = (date) => {
    date = new Date(date);
    setState({ date: date }, () => {
      _hideDateTimePicker();
      _calculateTheDifference();
    });
  };

  const _calculateTheDifference = () => {
    if (!state.date) {
      return;
    }
    let current_date = new Date().getDate();
    let current_month = new Date().getMonth();
    let current_year = new Date().getFullYear();
    let birth_date = state.date.getDate();
    let birth_month = state.date.getMonth();
    let birth_year = state.date.getFullYear();
    let month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (birth_date > current_date) {
      current_month = current_month - 1;
      current_date = current_date + month[birth_month - 1];
    }
    if (birth_month > current_month) {
      current_year = current_year - 1;
      current_month = current_month + 12;
    }
    let calculated_date = current_date - birth_date;
    let calculated_month = current_month - birth_month;
    let calculated_year = current_year - birth_year;
    if (calculated_date || calculated_month || calculated_year)
      setState({
        ...state,
        calculated_date: calculated_date,
        calculated_month: calculated_month,
        calculated_year: calculated_year,
        dateOpacity: 1,
      });
  };

  return <View>{/*Code here*/}</View>;
}

你不能将回调函数作为第二个参数传递给 setState 中的反应钩子(它只适用于 Class 组件),所以你可以改用useEffect 并控制您的应用程序生命周期。对于这种情况,您可以按照以下步骤操作:

React.useEffect(()=> {
   if ( state.date ){
     _hideDateTimePicker();
     _calculateTheDifference();
   };
} , [state])

并且您还需要将 _handleDatePicked 更改为 :

const _handleDatePicked = (date) => {
    date = new Date(date);
    setState({ 
       ...state,
       date: date 
    });
};

我通过 React Hooks 将您的代码重写为函数式编程,我还在 android 模拟器中对其进行了测试,它的工作很仔细。您可以在下面看到输出项目的示例:

以及项目代码:

import React from "react";
import {
  StyleSheet,
  Text,
  View,
  Dimensions,
  Platform,
  TouchableOpacity,
} from "react-native";
import DateTimePicker from "react-native-modal-datetime-picker";

const { height } = Dimensions.get("window");

const App = ()=> {

  const [states , setStates] = React.useState({
    calculated_date: undefined,
    calculated_month: undefined,
    calculated_year: undefined,
    dateOpacity: undefined
  });

  const [isDateTimePickerVisible , setIsDateTimePickerVisible] = React.useState(false);
  const [date , setDate] = React.useState(undefined);

  const _showDateTimePicker = () => setIsDateTimePickerVisible(true);
  
  const  _hideDateTimePicker = () => setIsDateTimePickerVisible(false);
  
  const _handleDatePicked = (date)=> {
    date = new Date(date);
    return setDate(date);
  };

  const _calculateTheDifference = () => {
    if (!date) {
      return;
    }

    const currentDate = new Date();

    let current_date = currentDate.getDate();
    let current_month = currentDate.getMonth();
    let current_year = currentDate.getFullYear();

    let birth_date = date.getDate();
    let birth_month = date.getMonth();
    let birth_year = date.getFullYear();

    let month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    
    if (birth_date > current_date) {
      current_month = current_month - 1;
      current_date = current_date + month[birth_month - 1];
    }

    if (birth_month > current_month) {
      current_year = current_year - 1;
      current_month = current_month + 12;
    }

    let calculated_date = current_date - birth_date;
    let calculated_month = current_month - birth_month;
    let calculated_year = current_year - birth_year;

    if (calculated_date || calculated_month || calculated_year)
      setStates({
        ...states,
        calculated_date,
        calculated_month,
        calculated_year,
        dateOpacity: 1,
      });
  };

  React.useEffect(()=>{
      if (date){
        console.log("Selected Date:" , date);
          _hideDateTimePicker();
          _calculateTheDifference();
      };
  } , [date]);

  return (
    <View style={styles.container}>
      <View style={styles.slider}>
        <View style={{ justifyContent: "center", alignItems: "center" }}>
          <Text style={styles.yasHesaplama}>Age Calculate</Text>
        </View>
      </View>
      <View style={{ flex: 1, backgroundColor: "#fff" }}>
        <View style={styles.solKose} />
        <View
          style={{
            flex: 1,
            backgroundColor: "#fff",
            borderTopLeftRadius: 65,
          }}
        />
      </View>
      <View style={styles.anaGovde}>
        <TouchableOpacity
          style={styles.touchableOpacity}
          onPress={_showDateTimePicker}
        >
          <Text style={styles.dogumGunu}>Enter your birthday.</Text>
        </TouchableOpacity>
        <View style={[styles.viewText, { padding: 10 }]}>
          <Text style={styles.text}>
            {states.calculated_year}
            {" Year"}{" "}
          </Text>
          <Text style={styles.text}>
            {states.calculated_month}
            {" Month"}{" "}
          </Text>
          <Text style={styles.text}>
            {states.calculated_date}
            {" Date"}{" "}
          </Text>
        </View>
      </View>
      <DateTimePicker
        isVisible={isDateTimePickerVisible}
        onConfirm={_handleDatePicked}
        onCancel={_hideDateTimePicker}
        mode={"date"}
        maximumDate={new Date()}
      />
    </View>
  );

};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
  slider: {
    ...Platform.select({
      ios: {
        height: 0.3 * height,
        backgroundColor: "#C12699",
        borderBottomRightRadius: 65,
      },
      android: {
        height: 0.3 * height,
        backgroundColor: "#009A88",
        borderBottomRightRadius: 65,
      },
    }),
  },
  text: {
    paddingHorizontal: 5,
    justifyContent: "center",
    alignItems: "center",
    fontSize: 30,
    fontWeight: "bold",
    color: "#fff",
  },
  viewText: {
    ...Platform.select({
      ios: {
        height: 150,
        width: Dimensions.get("window").height / 2.6,
        flexDirection: "row",
        backgroundColor: "#C12699",
        justifyContent: "center",
        alignItems: "center",
        borderRadius: 10,
      },
      android: {
        height: 120,
        width: Dimensions.get("window").height / 2,
        flexDirection: "row",
        backgroundColor: "#009A88",
        justifyContent: "center",
        alignItems: "center",
        borderRadius: 10,
        top: 40,
      },
    }),
  },
  dogumGunu: {
    ...Platform.select({
      ios: {
        fontSize: 20,
        color: "#fff",
        fontWeight: "bold",
        borderWidth: 2,
        borderColor: "#fff",
        borderRadius: 10,
        padding: 20,
      },
      android: {
        fontSize: 20,
        color: "#fff",
        fontWeight: "bold",
        borderWidth: 2,
        borderColor: "#fff",
        borderRadius: 10,
        padding: 10,
      },
    }),
  },
  yasHesaplama: {
    ...Platform.select({
      ios: {
        top: 100,
        fontSize: 40,
        color: "#fff",
        fontWeight: "bold",
        borderWidth: 2,
        borderColor: "#fff",
        borderRadius: 10,
        padding: 20,
      },
      android: {
        top: 50,
        fontSize: 35,
        color: "#fff",
        fontWeight: "bold",
        borderWidth: 2,
        borderColor: "#fff",
        borderRadius: 10,
        padding: 10,
      },
    }),
  },
  touchableOpacity: {
    ...Platform.select({
      ios: {
        height: 100,
        width: Dimensions.get("window").height / 3,
        backgroundColor: "#C12699",
        alignItems: "center",
        justifyContent: "center",
        borderRadius: 10,
      },
      android: {
        height: 80,
        width: Dimensions.get("window").height / 2.3,
        backgroundColor: "#009A88",
        alignItems: "center",
        justifyContent: "center",
        borderRadius: 10,
      },
    }),
  },
  anaGovde: {
    ...Platform.select({
      ios: {
        flex: 1,
        justifyContent: "space-between",
        alignItems: "center",
        bottom: 210,
      },
      android: {
        flex: 1,
        justifyContent: "space-between",
        alignItems: "center",
        bottom: 150,
      },
    }),
  },
  solKose: {
    ...Platform.select({
      ios: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: "#C12699",
      },
      android: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: "#009A88",
      },
    }),
  },
});