How would I re-use these functions instead of having one per textfield?

落爺英雄遲暮 提交于 2019-12-25 01:24:05

问题


I'm learning spfx using SPO. I have a form which has several text fields. I have 2 class components. (A and B) Each time a textfield on (B) is typed into, a function sends the return to a props file. (This is called Lifting State up I believe). These props are then used by a handler function in (A) so whatever is typed can be submitted to an SP list by (A). This all works fine. But I've noticed that I'm creating functions for each and every textfield. Can someone tell me a way to re-use a function. Here's one of the functions from (B):

private _onJobTitleChange = (ev: React.FormEvent<HTMLInputElement>, newValue?: string) => {
    this.setState({
      JobTitle: newValue
    });
  }

Here's a handler function from (A):

private _onJobTitleChange = (ev: React.FormEvent<HTMLInputElement>, newValue?: string) => {
    this.setState({
      JobTitle: newValue
    });
  }

As you can see the handler function sets the state so it can be submitted to the list.

If you need it here's the props file:

export interface IEvalReqNewProps {
  context: WebPartContext;
  description: string;
  jobTitleReportTo: string;
  onJobTitleReportToChange(value: string ): void;
  jobTitleReportToNum: string;
  onJobTitleReportToNumChange(value: string ): void;
  propGradeChange: string;
  onPropGradeChange(value: IDropdownOption): void;
  compPosTit1: string;
  onCompPostTit1Change(value: string ): void;
  compPosTit2: string;
  onCompPostTit2Change(value: string ): void;
  compPosTit3: string;
  onCompPostTit3Change(value: string ): void;

You can see I'm creating multiple function for these fields and it's getting messy. I'd appreciate a code example instead of a description of what to do. Thanks v much :)


回答1:


I believe you can handle it like this:

public handleMultipleFields = (field: string, value: string) => {
    const { foo } = this.state;
    this.setState({ [field]: value });
  };

ReactJS Docs

Another example if you have to update certain object in state:

public handleObjectWithMultipleFields = (field: string, value: string) => {
    const { myObject } = this.state;
    this.setState({ myObject: { ...myObject, [field]: value } });
  };


来源:https://stackoverflow.com/questions/58026987/how-would-i-re-use-these-functions-instead-of-having-one-per-textfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!