我应该将此方法设置为什么类型的事件?

时间:2018-03-22 16:59:49

标签: reactjs typescript

我应该将此组件的setEndpointState方法设置为什么类型的事件。我尝试将其设置为React.FormEvent<HTMLFormElement>,但后来我在setState函数中遇到类型错误,说我缺少道具namehostnamedescription。事件的类型是错误的还是有办法以不同的方式编写setState函数?

import * as React from "react";
import EditBasicInfoForm from "./EditBasicInfoForm";
import { Endpoint } from "../../Endpoints/model";

interface EditBasicInfoProps {
  editBasicInfo: (endpoint: Endpoint) => void;
  ocid: string;
}

interface EditBasicInfoState {
  name: string;
  hostname: string;
  description: string;
}

export class EditBasicInfo extends React.Component<EditBasicInfoProps & EditBasicInfoState, EditBasicInfoState> {
  constructor(props: any) {
    super(props);

    this.state = {
      name: "",
      hostname: "",
      description: ""
    };

    this.setEndpointState = this.setEndpointState.bind(this);
    this.editBasicInfo = this.editBasicInfo.bind(this);
  }

  public setEndpointState(e: React.FormEvent<HTMLFormElement>): void {
    const target = e.currentTarget;
    const value = target.value;
    const name = target.name;
    this.setState({
      [name]: value
    });
  }

  public editBasicInfo(): void {
    const endpoint: any = {
      name: this.state.name,
      hostname: this.state.hostname,
      description: this.state.description,
      ocid: this.props.ocid,
    };

    this.props.editBasicInfo(endpoint);
  }

  public render(): JSX.Element {
    return (
      <>
        <EditBasicInfoForm
          name={this.state.name}
          hostname={this.state.hostname}
          description={this.state.description}
          handleChange={this.setEndpointState}
          handleSubmit={this.editBasicInfo}
        />
      </>
    );
  }
}

export default EditBasicInfo;

2 个答案:

答案 0 :(得分:0)

注意 - 您的状态实现了接口EditBasicInfoState,因此每次setState时,它都需要提供实现该接口的完整状态。

您当前正在为其提供一个对象,该对象使用name作为动态键(即使在您的州也可能不存在),并且您缺少其余字段。

查看使用此对象{name: '', hostname: '', description: ''}设置状态是否会删除错误,只是为了确保这确实是问题。

如果这确实解决了你的问题,我建议回到Typescript中接口的含义,并阅读Partial

答案 1 :(得分:0)

这对我有用。谢谢你的帮助!

public setEndpointState(e: React.SyntheticEvent<HTMLInputElement>): void {
    const target = e.currentTarget;
    const name = target.name;
    const value = target.value;

    this.setState({
      ...this.state,
      [name]: value
    });
  }