react中受控組件相關的warning
阿新 • • 發佈:2019-04-02
idm 輸入框 設置 input 生命周期 elements com nbsp 方法
當ReactDOM檢測這個元素是不是受控時,它的判斷條件是value!=null,註意是!=而不是!==,
又由於undefined==null,所以判斷該組件是非受控組件
而我又在input元素上綁定了onChange方法改變了value,將它變成了受控組件,所以產生了報錯信息
在表單中,報如下的錯,意思是非受控的輸入框變成了受控的,報錯信息如下
Warning: A component is changing an uncontrolled input of type text to be controlled.Input elements should not switch from uncontrolled to controlled (or vice versa).
Decide between using a controlled or uncontrolled input element for the lifetime of the component.
我寫的代碼如下:
<input className="form-control" name="productName" placeholder="請輸入商品名稱" value={this.state.detail.productName || ""} onChange={(e)=>{this.inputValueChange(e)}} />
該元素將value綁定在this.state.detail對象中,obj對象在componentDidMount生命周期中進行初始化
原因:
因為在第一次render組件時,this.state.obj={},於是this.state.detail.productName為undefined,於是input接受到的就是value={undefined}
又由於undefined==null,所以判斷該組件是非受控組件
而我又在input元素上綁定了onChange方法改變了value,將它變成了受控組件,所以產生了報錯信息
解決辦法
在constructor中修改this.state,給detail設置一個默認的初始值,如下所示
this.state={ detail:{ productName: ‘‘, } }
react中受控組件相關的warning