簡體   English   中英

TypeScript React setState不起作用

[英]TypeScript React setState is not working

我有這樣的輸入組件

import * as React from 'react'

import { InputNumber, Button } from 'antd'

interface IProps {
  value: number
}

interface IState {
  value: number
}

class ConfirmInput extends React.Component<IProps, IState> {
  public readonly state = {
    value: 0
  }

  static getDerivedStateFromProps = ({ value }: IProps) => ({ value })

  public render () {
    return (
      <div>
        <InputNumber
          value={this.state.value}
          formatter={value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
          parser={(value): any => value && value.replace(/\$\s?|(,*)/g, '')}
          onChange={(value: number) => {
            console.log('value', value)
            this.setState({ value })
          }}
        />
        <Button
          onClick={() => console.log('this.state.value', this.state.value)}
          type="primary"
        >
          Bid
        </Button>
      </div>
    )
  }
}

export default ConfirmInput

在我更改的InputNumber上,它將獲取一個數字作為值,但是this.setState不會更改該值。 沒有編譯器錯誤,並且一切似乎都可以使用類型。 我在這里想念什么?

您需要將原始值存儲在狀態中,以便您的getDerivedStateFromProps實現僅在prop更改時才能覆蓋當前值。 希望這可以正常工作(未經測試):

interface IState {
  value: number
  origValue: number
}

class ConfirmInput extends React.Component<IProps, IState> {
  // ...
  static getDerivedStateFromProps = (props: IProps, state: IState) =>
    (props.value != state.origValue ? { origValue: props.value, value: props.value } : {})
  // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM