无法在 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>


MYYA
浏览 104回答 4
4回答

慕妹3146593

如果您有一个不受控制的组件,您可能需要使用该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" />`

Qyouu

在状态对象内设置默认值并将更改处理程序附加到输入以捕获更改:示例codesandbox:https://codesandbox.io/s/react-basic-class-component-22fl7class Demo extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; inputValue: 'l.h.thuong181@gmail.com'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;};&nbsp; }&nbsp; handleChange = event => {&nbsp; &nbsp; &nbsp; this.setState({ inputValue: event.target.value }, () =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(this.state.inputValue)&nbsp; &nbsp; &nbsp; );&nbsp; };&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp;<div className="form-group">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<label>Email:</label>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<input&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;className="form-input"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;type="text"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;value={this.state.inputValue}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;onChange={this.handleChange}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;name="email">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</input>&nbsp; &nbsp; &nbsp; &nbsp;</div>&nbsp; &nbsp; );&nbsp; }}

翻阅古今

这是如何在反应中使用输入的示例代码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

相关分类

Html5