如何将数据传递给父组件 React Native

时间:2021-04-13 18:00:46

标签: reactjs react-native

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

add_action( 'woocommerce_archive_description', function(){
    if( isset( $_GET['orderby'] ) && $_GET['orderby'] == 'date' ){
        echo '<h3>See Our Newest Products</h3>';
    }
} );

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

[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;

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

1 个答案:

答案 0 :(得分:1)

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

编辑

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

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

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

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

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