我有一个这样的输入组件
Scalar x /2/;
Display$(x>3) 'X is greater than 3';
Display$(x>1) 'X is greater than 1';
在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
并没有改变值。
没有编译器错误,并且一切似乎都可以使用类型。
我在这里想念什么?
答案 0 :(得分:0)
您需要将原始值存储在状态中,以便您的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 } : {})
// ...
}