与Typescript反应:类型不匹配

问题描述 投票:0回答:2

它有一段时间开始使用React与typescript,但总是与类型和React元素所期望的混淆。

就像在这种情况下(也是qazxsw poi)我得到了Todos组件的以下错误

在具有更漂亮和TSLint设置的VSCODE中:类型'(props:PropsWithChildren)=> Element []'不能分配给'FunctionComponent'类型。

在Sandbox中:类型'(props:Props)=> void []'不能分配给'FunctionComponent'类型。


sandbox here

用于待办事项的Mobx商店就像

    import { TodoStore } from "./stores/TodoStore";
    import { observable } from "mobx";
    interface IProps {
      todoStore: TodoStore;
    }
   // red underline at `TodoComp` with mentioned error message
    const TodosComp: React.FC<IProps> = props => {
      const { todos } = props.todoStore;
      return todos.map(todo => {
        <div key={todo.id}>
          <p>{todo.title}</p>
          <select />
        </div>;
      });
    };
    export default inject("todoStore")(observer(TodosComp));

来自Mobx的问题是否将类本身用作组件中的类型? mobx类需要一个单独的接口吗?

另外,作为一个特定于Mobx的问题,沙盒是否正确地在提供者处实例化商店类?

一般来说,如果有人知道一篇关于React with typescript的好文章如何管理道具和JSX类型将不胜感激。

reactjs typescript mobx-react react-tsx
2个回答
2
投票

函数应该返回一个JSX.Element,你需要传递div或Fragment,这应该有效。

import { decorate, observable, runInAction, action } from 'mobx';
export interface ITodo {userId: number; id: number; title: string; completed: boolean;
}
export class TodoStore {
  public todos: ITodo[];
  constructor() {
    this.todos = [];
    this.fetchTodos();
  }

  public async fetchTodos() {
    const response = await fetch('http://jsonplaceholder.typicode.com/todos');
    const todos: ITodo[] = await response.json();
    runInAction(() => {
      this.todos = todos;
    });
 }}
decorate<TodoStore>(TodoStore, { todos: observable, fetchTodos: action });

1
投票

const Todos: React.FC<IProps> = (props: IProps): JSX.Element => { const { todos } = props.todoStore; return (<React.Fragment> {todos.map(todo => { <div key={todo.id}> <p>{todo.title}</p> <select /> </div>; })} </React.Fragment>); }; 定义为

FunctionComponent

interface FunctionComponent<P = {}> { (props: PropsWithChildren<P>, context?: any): ReactElement | null; ... 在哪里

ReactElement

通过查看这些定义,您可以告诉您无法从interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> { type: T; props: P; key: Key | null; } 返回数组。解决方案是将返回值包装在反应片段中

React.FC
© www.soinside.com 2019 - 2024. All rights reserved.