我已经阅读了与这个问题相关的所有堆栈溢出问题,还有这个官方反应帖子和首选解决方案。
不建议再使用componentWillReceiveProps
了!
在将此问题标记为重复之前,请理解我的具体问题,我没有看到针对我的具体问题的任何解决方案。
我想做的很简单:
我有组件KInputRange
从道具接收值并将值发送出去(回调)onEnter事件(仅在输入时将值发送到服务器)props.value可以随机更改(即将到来通过来自服务器的 websocket)
我的问题:
在我的组件中,<input>
value 属性将从props
或从获取数据state
?
如果来自道具: 当用户键入输入数据时,如何在内部更新值?
如果来自状态: 如果 props.value 从服务器随机更改,我如何更新新值?
我实际上需要在道具更改时更新我的内部状态,但是如果反应说这是反模式,今天该怎么做?
到目前为止,这是我的代码:
class KInputRange extends React.Component<any, any> {
constructor(props: any) {
super(props);
}
private onKeyDown(e: any): void {
//If the key is enter call to props.onEnter with the current value
}
private onChange(e: any): void {
//if user change the value- change the internal value
}
public render() {
return (
<input value={?????} type="text" onChange={(e) => this.onChange(e)} onKeyDown={(e) => this.onKeyDown(e)}/>
);
}
}
用法:
<KInputRange value={this.state.dataFromTheServer} onEnter={(val: number) => this.kInputRangeEnterClicked(val)}/>