Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

reactjs - Why do we add " ( ) => " before a function reference?

I am learning typescript and was trying to implement a detailList component from Microsoft Fluent UI, but I ran into some trouble:

Type '(ev: React.MouseEvent<HTMLElement>, checked: boolean) => void' is not assignable to type '(event: MouseEvent<HTMLElement, MouseEvent>, checked?: boolean | undefined) => void'.

In the code there was a function called _onChangeCompactMode being referenced when a toggle button is clicked

  private _onChangeCompactMode = (ev: React.MouseEvent<HTMLElement>, checked: boolean): void => {
this.setState({ isCompactMode: checked });

Here is where it's referenced:

  <Fabric>
    <div className={classNames.controlWrapper}>
      <Toggle
        label="Enable compact mode"
        checked={isCompactMode}
        onChange={this._onChangeCompactMode}
        onText="Compact"
        offText="Normal"
        styles={controlStyles}
      />
       ...
  </Fabric>

I fixed this issue by changing this line onChange={this._onChangeCompactMode} to this onChange={() => this._onChangeCompactMode}

I am not sure why this made it work. My understanding is, I passed a function reference. But why wouldn't it work as it is without () =>

Still new here, so constructive feedback is welcomed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is because the types don't match. Have a look at the toggle documentation

onChange has the type:

(event: React.MouseEvent<HTMLElement>, checked?: boolean) => void

Note that the checked is optional, but in your implementation it's not. It should work if you make it optional:

private _onChangeCompactMode = (ev: React.MouseEvent<HTMLElement>, checked?: boolean): void => {
this.setState({ isCompactMode: checked ?? false });

Make sure to add a default now that checked is optional, like I did with checked ?? false


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...