简体   繁体   English

Typescript React 将参数传递给 setState

[英]Typescript React Passing parameter to setState

I am a beginner and I am doing this...我是初学者,我正在这样做......

<i className="fa fa-trash-alt" onClick={() => this.handleDelete("trippurpose")} />

My handle delete is written like this...我的句柄删除是这样写的...

handleDelete(whichitem: string) {
    // this handles someone changing an input text field
    console.log(whichitem);

    if (whichitem === "trippurpose") {
      this.setState({
        trippurpose: "",
      });
    } else if (whichitem === "projecttask") {
      this.setState({
        projecttask: "",
      });
    }
  }

What's I'd prefer to do is...我更愿意做的是...

  handleDelete(whichitem: string) {
    // this handles someone changing an input text field

      this.setState({
        [whichitem]: "",
      });
  
    }

But when I do that I get an error... Argument of type `{[x: string]: string;但是当我这样做时,我得到一个错误... `{[x: string]: string; 类型的参数}' is not assignable to parameter of type 'TemplatePopoverState | }' 不能分配给“TemplatePopoverState |”类型的参数((prevState: Readonly, props... and much more... ((prevState: Readonly, props... 还有更多...

From reading up it seems that doing the [whichitem].从阅读来看,似乎在做 [whichitem]。

      this.setState({
        [whichitem]: "",
      });

Is the correct way to go but I suspect it's something in the method parameters that is wrong - any hints? go 的正确方法是正确的方法,但我怀疑方法参数中的某些东西是错误的 - 有什么提示吗? As I said I am a complete novice..The ultimate goal is to call a function that pass a string that reflects the value of the input text field I want to clear (set to "").正如我所说,我是一个完全的新手..最终目标是调用一个 function 传递一个字符串,该字符串反映了我要清除的输入文本字段的值(设置为“”)。

While setting dynamic value to setState, you need to specify the key to be one among the state keys, you can write the above funcition like将动态值设置为 setState 时,您需要将键指定为 state 键之一,您可以将上述函数编写为

handleDelete(whichitem: keyof TemplatePopoverState) {
    // this handles someone changing an input text field

      this.setState({
        [whichitem]: "",
      } as Pick<TemplatePopoverState, keyof TemplatePopoverState>);
  
    }

For more reference referthis github issue .如需更多参考,请参阅此 github 问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM