gpt4 book ai didi

javascript - 我应该如何在没有 "Warning: Failed prop type: You provided a ` 处理程序的情况下避免将此 `onChange` 值 Prop 用于表单字段。”

转载 作者:行者123 更新时间:2023-11-30 06:50:40 25 4
gpt4 key购买 nike

似乎在 React 中<input>具有 value 属性的必须有一个 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. 获取输入字段中键入的每个键的最佳方法应该是onKeyXXX like onKeyPress or onKeyDown(我获取 key 失败来自 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;

关于javascript - 我应该如何在没有 "Warning: Failed prop type: You provided a ` 处理程序的情况下避免将此 `onChange` 值 Prop 用于表单字段。”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51303157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com