当我们在多选框上设置了checked属性,却没有onChange处理函数时,会产生"You provided acheckedprop to a form field without anonChangehandler"错误。为了解决该错误,可以使用defaultChecked属性,或者在表单字段上设置onChange属性。 you-provided-checked-prop-to-form-field.png 这里有个例子用来展示错误是如何发生的。
添加onChange来更新state 代码如下: export defaultclassBasicInput extends Component{constructor(props){super(props);this.state={names:[],name:''};}onNameChange=(e)=>{this.setState({name:e.target.value});}onFormSubmit=(e)=>{e.preventDefault()constname=this.state.nameconstnames=[...this.stat...
Warning: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`. 您为表单字段提供了一个没有onChange处理程序的value属性,这将呈现只读字...
from'react-dom/client';functionMyForm(){const[name,setName]=useState("");return(<form><label>Enter your name:<inputtype="text"value={name}onChange={(e)=>setName(e.target.value)}/></label></form>)}constroot=ReactDOM.createRoot(document.getElementById('root'));root.render(<MyForm/>...
React.FormEvent<>除了使用and键入参数和返回值void,您还可以将类型应用于事件处理程序本身 // 在 = 的左侧输入onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {this.setState({text: e.currentTarget.value})} 键入onSubmit,在表单中包含不受控制的组件 ...
这里给onChange方法定义了方法的类型,它是一个ChangeEventHandler的类型,并且作用的对象是一个HTMLImnputElement类型的标签(input标签)。 五、HTML标签类型 1. 常见标签类型 在项目的依赖文件中可以找到HTML标签相关的类型声明文件: 所有的HTML标签的类型都被定义在 intrinsicElements 接口中,常见的标签及其类型如下: ...
type="text"name="name"id="name"value={this.state.name}onChange={this.handleNameChange}/></section></form><p>Hello{this.state.name}</p></section>);}} 注:如果你是通过 Create React App 创建项目,只需要将 App.js 里的内容替换成上述内容即可。
如果在form中有多个输入框的情况下,我们仍然采用上面的方法为每个input增加一个对应的state,并且为每个input增加onChange方法,整个程序要变得非常的繁重。建立一个一对一的input=>state=>handler并不是一件理想的事情。 如何才能让input元素变得便于维护和管理呢?
Uncontrolled inputsare like traditional HTML form inputs:(翻译:非受控就像传统的HTML表单输入,如下:) classFormextendsComponent{render(){return(<div><input type="text"/></div>);}} They remember what you typed. You can then get their value usinga ref. For example, inonClickhandler of a but...
You can then use the onChange event handler on each input element to update the corresponding state variable: <Input name="name1" value={item1} onChange={(e) => setItem1(e.target.value)} /> When the form is submitted, you can use the setGroup1, setGroup2, setSe...