So I've recently discovered that callbacks for event handlers are bad for rendering performance: .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.
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 plain about the input element having a name
attribute that is not a 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>
);
}
}
So I've recently discovered that callbacks for event handlers are bad for rendering performance: https://reactjs/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.
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 plain about the input element having a name
attribute that is not a 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>
);
}
}
Share
Improve this question
edited Feb 16, 2021 at 20:12
xy2_
7,1923 gold badges20 silver badges34 bronze badges
asked Apr 23, 2018 at 1:35
typeofChristypeofChris
631 silver badge6 bronze badges
1 Answer
Reset to default 5You are explicitly casting your name
property as a key of State
, so it is normal that the piler does not plain.
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>
);
}
}