首页 > 解决方案 > Reactjs+Flow:SyntheticKeyboardEvent 并将函数作为道具传递

问题描述

我有以下 AsyncApp.js 组件

AsyncApp.js
// @flow
import React from "react";
import { connect } from "react-redux";
import _ from "lodash";
import { fetchPastLaunchesRequest } from "../actions/launches";
import { LaunchList } from "../components/launches/LaunchList";
import { Picker } from "../components/Picker";

type Props = {
  fetchPastLaunchesRequest: (launch_year: string) => Function,
  launches: Array<Object>,
  hasErrored: boolean,
  isLoading: boolean
};

class AsyncApp extends React.Component<Props, void> {
  componentDidMount() {
    let launch_year = "";
    this.props.fetchPastLaunchesRequest(launch_year);
  }

  handleOnChange = (e: SyntheticKeyboardEvent<HTMLInputElement>) => {
    this.props.fetchPastLaunchesRequest(e.currentTarget.value);
  };

  render() {
    const { launches, isLoading } = this.props;
    let launchYears = _.range(2005, 2019);
    return (
      <div id="launches">
        <Picker options={launchYears} onChange={this.handleOnChange} />
        {isLoading && launches.length === 0 && <h2>Loading...</h2>}
        {launches.length > 0 ? <LaunchList launches={launches} /> : <div />}
      </div>
    );
  }
}

const mapDispatchToProps = (dispatch: *) => {
  return {
    fetchPastLaunchesRequest: launch_year =>
      dispatch(fetchPastLaunchesRequest(launch_year))
  };
};

const mapStateToProps = state => {
  return {
    launches: state.launches.items,
    hasErrored: state.itemsHasErrored,
    isLoading: state.itemsIsLoading
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(AsyncApp);

选择器.js

//@flow

import React from "react";

type PickerProps = {
  options: Object,
  onChange: (e: HTMLInputElement) => void
};

export const Picker = ({ options, onChange }: PickerProps) => {
  return (
    <span>
      <select onChange={e => onChange(e)}>
        <option defaultValue=" ">Pick Year</option>
        {options.map(year => (
          <option value={year} key={year}>
            {year}
          </option>
        ))}
      </select>
    </span>
  );
};

我在 AsyncApp.js 组件中不断收到这种类型检查错误:

[flow] Cannot create `Picker` element because `SyntheticKeyboardEvent` [1] is incompatible with `HTMLSelectElement` [2] in the first argument of property `onChange`. (References: [1] [2])
(property) AsyncApp.handleOnChange: (e: any) => void
[Flow]
handleOnChange: (e: SyntheticKeyboardEvent < HTMLInputElement > ) => void

标签: reactjs

解决方案


将 onChange 的参数类型更改为HTMLInputElement

//@flow

import React from "react";

type PickerProps = {
  options: Object,
  onChange: (e: HTMLInputElement) => void
};

export const Picker = ({ options, onChange }: PickerProps) => {
  return (
    <span>
      <select onChange={e => onChange(e)}>
        <option defaultValue=" ">Pick Year</option>
        {options.map(year => (
          <option value={year} key={year}>
            {year}
          </option>
        ))}
      </select>
    </span>
  );
};

推荐阅读