无法从React Component内部的函数访问道具

时间:2020-04-15 13:17:08

标签: javascript reactjs

我正在尝试构建一个提醒应用程序(不像我想的那么简单!)。

我的时间选择器组件在几个地方使用过,所以我试图向它发送一个id用作键值。我将此ID设置为父母中的道具。

我的问题是如何将其用作异步函数的键值?

这是代码。...

export default class Picker extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isDateTimePickerVisible: false,
      isDarkModeEnabled: false,
      chosenTime: "00:00",
    };
  }

  showDateTimePicker = (date) => {
    // this.isDark();
    this.setState({ isDateTimePickerVisible: true });
    // PushNotifactions();
  };

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

  setTime = (time) => {
    this.setState({ chosenTime: time });
  };

  async handleDatePicked(time) {
    try {
      let timePicked = moment(time, "hmm").format("HH:mm");
      await AsyncStorage.setItem(this.props.pickerId, timePicked);
      console.log("handle date picked");
      this.setTime(timePicked);
      console.log(this.state.chosenTime);

      this.hideDateTimePicker();
    } catch (error) {
      console.log(error);
    }
  }

  render() {
    return (
      <View>
        <TouchableOpacity
          style={{
            backgroundColor: this.props.pickerColor,
            width: 80,
            height: 50,
            padding: 5,
            justifyContent: "center",
            borderRadius: 15,
          }}
          onPress={this.showDateTimePicker}
        >
          <Text style={styles.btnText}>{this.state.chosenTime}</Text>
          {/* {console.log(newTime)} */}
        </TouchableOpacity>
        <DateTimePicker
          isVisible={this.state.isDateTimePickerVisible}
          onConfirm={this.handleDatePicked}
          onCancel={this.hideDateTimePicker}
          mode={"time"}
          titleIOS={""}
          isDarkModeEnabled={this.state.isDarkModeEnabled}
          input={true}
        />
        <TimerNotification />
      </View>
    );
  }
}

这是父组件。

<View style={styles.morningSelector}>
            <OptionsDT
              optionText={"Morning reminder"}
              switchColor={"#f6c532"}
              style={{ width: "100%" }}
              pickerColor={"#f6c532"}
              start={"00:00"}
              end={"12:00"}
              pickerId={"morningReminder"}
            />
          </View>
          <View style={styles.eveningSelector}>
            <OptionsDT
              optionText={"Evening reminder"}
              switchColor={"#f6c532"}
              style={{ width: "100%" }}
              pickerColor={"#f6c532"}
              start={"12:00"}
              end={"00:00"}
              pickerId={"eveningReminder"}
            />
          </View>

1 个答案:

答案 0 :(得分:0)

您需要将handleDatePicked函数绑定到组件或将其转换为箭头函数。

解决方案1-在构造函数内部绑定函数:

constructor(props) {
    super(props);
    this.handleDatePicked.bind(this)
}

解决方案2-将您的函数转换为箭头函数:

handleDatePicked = async () => {
    //your function code..
}

了解有关将功能绑定到组件here

的更多信息