类型'(event:FormEvent <htmlinputelement>)=>无效'不能分配给类型'()=>任何'

时间:2019-02-21 06:13:33

标签: javascript reactjs typescript

  

类型'(event:FormEvent)=>无效'不能分配给类型'()=>任何'。

在我的父组件中,我只是向孩子传递了一个处理onChange的函数:

<SearchInput handleSearchTyping={this.handleSearchTyping}/>

@bind
handleSearchTyping(event: React.FormEvent<HTMLInputElement>) {
  const target = event.target as HTMLInputElement;
  const { value: searchText } = target;

  const search = (text: string) => {
    const { searchList } = this.state;
    const searchedCoins = findAsset(text, searchList);
    this.setState({ searchList: searchedCoins });
  };

  const clearSearch = () => {
    this.setState({ searchList: this.state.saved });
  };

  const handleUpdate = (num: number) => (num > 1 ? search(searchText) : clearSearch());

  return handleUpdate(searchText.length);
}

孩子:SearchInput:

import React from 'react'

export const SearchInput = (props: { handleSearchTyping(): void }) =>
  <input type="text" placeholder="Search here" onChange={props.handleSearchTyping} />;

enter image description here

也尝试过:

interface IProps {
  handleSearchTyping(): void;
}

export const SearchInput = (props: IProps) =>
  <input type="text" placeholder="Search here" onChange={props.handleSearchTyping} />;

插入SearchInput道具中的正确类型是什么?

1 个答案:

答案 0 :(得分:0)

啊,刚刚修好了

import React from 'react'

interface IProps {
  handleSearchTyping(event: React.FormEvent<HTMLInputElement>): void;
}

export const SearchInput = (props: IProps) =>
  <input type="text" placeholder="Search here" onChange={props.handleSearchTyping} />;

需要使用event: React.FormEvent<HTMLInputElement>类型。