簡體   English   中英

我應該如何避免這種“警告:道具類型失敗:您在沒有onChange處理程序的情況下為表單字段提供了一個value道具。”

[英]How should I avoid this “Warning: Failed prop type: You provided a `value` prop to a form field without an `onChange` handler.”

似乎在React中,每個具有value屬性的<input>必須具有onChange處理函數。 我想知道以下代碼段中的最佳做法是什么,以避免產生無聊的信息。

 import React,{Component} from 'react'; class SpellTest extends Component { constructor(props){ super(props); this.state={ chars:Array.from(props.word,()=>{return "?"}) }; this.handleInput=this.handleInput.bind(this); } handleInput(e){ let key=e.key this.setState(preState=>{return {chars:preState.chars.map((k,i)=>{return this.props.word.charAt(i)===key?key:k})};}) } render(){ return <div> <h1>{this.props.hint}</h1> <input value={this.state.chars.join("")} onKeyPress={this.handleInput} onChange={()=>{}}/> </div> } } export default SpellTest; //usage: //<SpellTest word="hello" hint="你好"/> //https://create-react-client.glitch.me/spell 

我問這個問題的原因如下:

  1. 獲取輸入到輸入字段中的每個鍵的最佳方法應該是onKeyXXXonKeyPressonKeyDown (我無法從onChange獲取鍵值)
  2. React抱怨缺少onChange ,這意味着應該有一種模式可以讓onChangeonKeyXXX處理程序配合使用,但是我不知道如何

最終我意識到Chrome android不支持keypress事件。 因此,我必須將代碼更改如下:

 import React,{Component} from 'react'; class SpellTest extends Component { constructor(props){ super(props); this.state={ chars:Array.from(props.word,()=>{return "?"}) }; this.handleChange=this.handleChange.bind(this); } handleChange(e){ let str=e.target.value; let str2=this.state.chars.join(""); let index=[...str].findIndex((k,i)=>{return str.slice(0,i)+str.slice(i+1)===str2}) if(index!==-1){ this.setState(preState=>{return {chars:preState.chars.map((k,i)=>{return this.props.word.charAt(i)===str[index]?str[index]:k})};}) } } render(){ return <div> <h1>{this.props.hint}</h1> <input value={this.state.chars.join("")} onChange={this.handleChange}/> </div> } } export default SpellTest; 

輸入應具有onChange才能知道如何更改value數據。 只需將onKeyPress更改為onChange ,一切就可以正常工作。

暫無
暫無

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

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