首页 > 解决方案 > 如何将数据传递给父组件 React Native

问题描述

我是原生反应新手,我正在使用它开发我的最后一年项目。尝试获取子组件的值时遇到问题。我用 DateTimePicker 制作了自己的组件(仅显示日期),然后我在另一个屏幕中使用这个日期选择器。使用选择器选择新值时,我想将此新值存储在父状态中。我在网上做了一些研究,发现我需要将数据从孩子传递给父母。我试过这样做,但现在我收到以下错误:

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_this.props.onSelectDate')]

您可以在下面找到我的代码:父组件:

import { Button, StyleSheet, Text, TextInput, View, TouchableWithoutFeedback, Keyboard} from "react-native";
import RadioForm, {RadioButton, RadioButtonInput, RadioButtonLabel} from 'react-native-simple-radio-button';

import AppDatePicker from '../components/AppDatePicker';
import AppTimePicker from '../components/AppTimePicker';

var radio_field_type = [
  {label: 'Natural Turf', value: 0 },
  {label: 'Artificial Turf', value: 1 }
];

class CreateGameScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      gameDate: ""
    }
  }
  handleNewDate(dateValue) {
    this.setState({gameDate: dateValue});
  }
  render() {
    return (
  <TouchableWithoutFeedback 
  onPress={() => Keyboard.dismiss()}>
  <View style={styles.container}>
     <View style={styles.header}>
        <Text style={styles.headerTitle}>
            <Text style={{color: 'black'}}>Create Game</Text>
        </Text>
    </View>
    <View style={{margin: 3}}>
    <AppDatePicker style={styles.pickerButton}
      onSelectDate={this.handleNewDate}
    ></AppDatePicker>
    <Text>{this.state.gameDate}</Text>
    </View> 
  </View>
  </TouchableWithoutFeedback>
  );
  }}

export default CreateGameScreen;

这是子代码:

import {View, Button, Platform, TouchableOpacity, Text} from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
import { MaterialCommunityIcons } from '@expo/vector-icons';

export const AppDatePicker = (props) => {
  const [date, setDate] = useState(new Date(1598051730000));
  const [mode, setMode] = useState('date');
  const [show, setShow] = useState(false);

  const handleOnChange = (event, selectedDate) => {
    const currentDate = selectedDate || date;
    this.props.onSelectDate(currentDate);
    setShow(Platform.OS === 'ios');
    setDate(currentDate);
  };

  const showMode = (currentMode) => {
    setShow(true);
    setMode(currentMode);
  };

  const showDatepicker = () => {
    showMode('date');
  };

  return (
    <View>
      <View>
        <TouchableOpacity onPress={showDatepicker} style={{borderWidth: 1, borderColor: 'black', flexDirection: 'row',   height: 40}}>
        <Text style={{marginBottom: 6, fontSize: 16,marginLeft: 10, alignSelf: 'center'}}>Please select the game date</Text>
        <View style={{position: 'absolute', right: 0, alignSelf: 'center'}}>
        <MaterialCommunityIcons name="calendar" size={35} color="black"/>
        </View>
        </TouchableOpacity>
      </View>
      {show && (
        <DateTimePicker
          testID="dateTimePicker"
          value={date}
          mode={mode}
          is24Hour={true}
          display="default"
          onChange={handleOnChange}
        />
      )}
    </View>
    
  );
};

export default AppDatePicker;

我真的很感激任何帮助。提前致谢

标签: reactjsreact-native

解决方案


this.props.onSelectDate(currentDate)应该props.onSelectDate(currentDate)在子组件中。仅this在类组件中使用。您的子组件是一个功能组件。

编辑

您还必须handleNewDate(dateValue)在构造函数中绑定您的。在你的构造函数中添加这个:

this.handleNewDate = this.handleNewDate.bind(this)

或者您也可以将您的函数声明为箭头函数,如下所示:

handleNewDate = (dateValue) => {
    // your logic
  };

然后在<Text>组件中渲染日期时。确保日期值是字符串类型而不是日期类型。因为 RN<Text>组件只接受字符串值。


推荐阅读