简体   繁体   English

与打字稿反应 - 使用 setState 进行类型安全

[英]React with typescript - type safety with setState

So I've recently discovered that callbacks for event handlers are bad for rendering performance: https://reactjs.org/docs/handling-events.html所以我最近发现事件处理程序的回调对渲染性能不利: https : //reactjs.org/docs/handling-events.html

I'm trying to heed this by grabbing the properties off the event in a class method rather than doing something like: onClick={({value}) => this.setState({"someProperty" as keyof State: value})} etc.我试图通过在类方法中从事件中获取属性而不是执行以下操作来注意这一点: onClick={({value}) => this.setState({"someProperty" as keyof State: value})}等。

However now that I can't explicitly declare typesafety in that callback, I'm trying to be dynamic about it and my typechecker is okay with the code below, but how can I make it complain about the input element having a name attribute that is not a keyof State ?但是,现在我无法在该回调中显式声明类型安全性,我正在尝试对其进行动态处理,并且我的类型检查器对下面的代码没问题,但是如何让它抱怨具有name属性的输入元素不是keyof State

interface State {
  someProperty: string;
}

class MakeMeSafer extends React.Component<{}, State> {

  state: State = {
    someProperty: ''
  }

  set = ({ currentTarget: { name, value } }: React.SyntheticEvent<HTMLInputElement>): void => {
    this.setState({ [name as keyof State]: value });
  }

  render(): JSX.Element {
    return (
      <div>
        <input type="text" name="some-name-not-in-state" onChange={this.set} />
      </div>
    );
  }

}

You are explicitly casting your name property as a key of State , so it is normal that the compiler does not complain.您明确地将您的name属性转换为State的键,因此编译器不会抱怨是正常的。

If you need type safety I would use a closure instead:如果您需要类型安全,我会使用闭包:

interface State {
  someProperty: string;
}

class MakeMeSafer extends React.Component<{}, State> {

  state: State = {
    someProperty: ''
  }

  onChange = (name: keyof State) =>
    (e: React.FormEvent<HTMLInputElement>) => {
      const newValue = e.currentTarget.value;
      this.setState({name: newValue});
    }
  }

  render(): JSX.Element {
    return (
      <div>
        <input type="text" onChange={this.onChange('some-name-not-in-state')} />
      </div>
    );
  }
}

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

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