无法在 React 中编辑输入元素的值

我的 React 项目有问题,我有一个如下所示的输入元素,但我无法编辑输入的文本。我只能在删除 value 属性时编辑输入文本,但我想要一个默认值。


  <div className="form-group">

       <label>Email:</label> 

       <input  

          className="form-input" 

          type="text" 

          value="l.h.thuong181@gmail.com" 

          name="email">

       </input>

  </div>


小怪兽爱吃肉
浏览 276回答 3
3回答

慕慕森

如果您有一个不受控制的组件,您可能希望使用该defaultValue属性而不是value(请参阅此参考)

当年话下

您可以使用useRef或defaultValueimport React, { useRef, useEffect } from "react";const input = useRef();useEffect(() => {&nbsp; &nbsp; input.current.value = "l.h.thuong181@gmail.com";}, []);<input ref={input} className="form-input" type="text" name="email" />`

萧十郎

这是一个示例代码如何在反应中使用输入class NameForm extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {value: ''};&nbsp; &nbsp; this.handleChange = this.handleChange.bind(this);&nbsp; &nbsp; this.handleSubmit = this.handleSubmit.bind(this);&nbsp; }&nbsp; handleChange(event) {&nbsp; &nbsp; this.setState({value: event.target.value});&nbsp; }&nbsp; handleSubmit(event) {&nbsp; &nbsp; alert('A name was submitted: ' + this.state.value);&nbsp; &nbsp; event.preventDefault();&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <form onSubmit={this.handleSubmit}>&nbsp; &nbsp; &nbsp; &nbsp; <label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" value={this.state.value} onChange={this.handleChange} />&nbsp; &nbsp; &nbsp; &nbsp; </label>&nbsp; &nbsp; &nbsp; &nbsp; <input type="submit" value="Submit" />&nbsp; &nbsp; &nbsp; </form>&nbsp; &nbsp; );&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript