javascript - react : Edit Textbox which has already value in it

标签 javascript reactjs

我是 ReactJS 的新手。我陷入了一个问题。我通过调用具有预定义值的 API 获取文本框值。但是当我尝试编辑它的值时,它不允许我编辑。

class TextEditor extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      emailIdValue: ""
    };
  }

  onKeyPress = e => {
    const regEx = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    if (e.target.value === "" || !regEx.test(e.target.value)) {
    
    } else {
      this.setState({
        emailIdValue: e.target.value
      });
    }
  };

  render() {
    return (
      <div>
        <input
          type="text"
          value="this.props.getValue"
          onChange={e => this.keyPress(e)}
        />
      </div>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

我在 this.props.getValue 中得到 abc@xyz.com

如何编辑文本框的值。

任何帮助都会很棒。

谢谢。

最佳答案

您可以在创建组件状态时将 this.props.getValue 值放入 TextEditor 组件状态,然后更改它:

class TextEditor extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      emailIdValue: props.getValue
    };
  }

  // ...

  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.emailIdValue}
          onChange={this.onKeyPress}
        />
      </div>
    );
  }
}

关于javascript - react : Edit Textbox which has already value in it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51246677/

相关文章:

javascript - jQuery:使用切片选择元素

javascript - 如何共享延续的中间结果?

javascript - 网格单元格的边框在 native react 中并不统一

javascript - 更新嵌套数组中的属性值(redux 状态)

javascript - 如何将 props 发送到组件以响应条件?

reactjs - 导航链接上的 activeClassName 不起作用 - react

javascript - 我的服务器端 php 没有从我的客户端 AJAX 请求中获取数据

javascript - 如何在继续之前等待 element.all().each() 解决

javascript - 如何更新所有相似的 DOM 元素?

reactjs - js-cookie enzyme 测试在测试 cookie.set 函数时失败