![](/img/trans.png)
[英]Failed prop type: You provided a `checked` prop to a form field without an `onChange` handler
[英]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
我問這個問題的原因如下:
onKeyXXX
如onKeyPress
或onKeyDown
(我無法從onChange
獲取鍵值) onChange
,這意味着應該有一種模式可以讓onChange
與onKeyXXX
處理程序配合使用,但是我不知道如何 最終我意識到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.