如何通过ref按组件?

时间:2016-12-02 13:52:59

标签: reactjs react-native react-jsx jsx ref

我正在尝试使用onSubmitEditing = {()=>打开日期选择器this.refs.date.press()}但按,onPress或单击不是函数。通过ref按压组件的功能是什么?

    <View>
      <Text>Apellido</Text>
      <TextInput ref="lastname" onSubmitEditing={() => this.refs.date.click()} onChangeText={(lastname) => this.setState({ lastname })} returnKeyType="next" />
    </View>
    <View>
      <Text>Fecha nacimiento</Text>
      <DatePicker
        ref="date"
        date={this.state.date}
        onDateChange={(date) => this.setState({ date })}
        />
    </View>

1 个答案:

答案 0 :(得分:0)

解决方案是调用在内部显示DatePicker的函数。

SignUp.js

    <View>
      <Text>Apellido</Text>
      <TextInput ref="lastname" onSubmitEditing={() => this.refs.date.showPicker()} onChangeText={(lastname) => this.setState({ lastname })} returnKeyType="next" />
    </View>
    <View>
      <Text>Fecha nacimiento</Text>
      <DatePicker
        ref="date"
        date={this.state.date}
        onDateChange={(date) => this.setState({ date })}
        />
    </View>

DatePicker.js

import React, { Component } from 'react';
import moment from "moment";
import {
  DatePickerAndroid,
  Text,
  TouchableWithoutFeedback,
  View,
} from 'react-native';
export default class DatePicker extends Component {
  constructor(props) {
    super(props);
    this.state = {
      date: props.date,
      text: moment(props.date).format('DD/MM/YY'),
      maxDate: props.maxDate,
      minDate: props.minDate,
    };
  }

  async showPicker() {
    try {
      const {action, year, month, day} = await DatePickerAndroid.open(
        { date: this.props.date, maxDate: this.props.maxDate, minDate: this.props.minDate }
      );
      if (action !== DatePickerAndroid.dismissedAction) {
        var date = new Date(year, month, day);
        this._onDateChange(date);
      }
    } catch ({code, message}) {
      console.warn('Error in example ' + message);
    }
  }
  _onDateChange(date) {
    var text = moment(date).format('DD/MM/YY');
    this.props.onDateChange(date);
    this.setState({
      text,
      date
    });
  }
  render() {
    return (
      <TouchableWithoutFeedback onPress={() => this.showPicker()}>
        <View >
          <Text style={this.props.style}>{this.state.text}</Text>
        </View>
      </TouchableWithoutFeedback>
    );
  }
}
DatePicker.defaultProps = {
  date: new Date(),
  minDate: new Date(1900, 1, 1),
  maxDate: new Date(2016, 11, 1)
};