反应输入光标的位置移到末尾?

时间:2018-12-17 22:32:50

标签: reactjs

我遇到了这种情况,我想在调用onChange之前“清理”输入,但是即使不重新渲染,光标也会移到末尾。为什么?

class Input extends React.Component {
  state = { value: this.props.value };

  onChange = e => {
    let nextValue = e.target.value;

    if (!/[0-9]/.test(nextValue)) {
      this.setState({ value: nextValue });
    }
  };

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

ReactDOM.render(<Input value="type something here" />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

1 个答案:

答案 0 :(得分:1)

您可以使用onKeyPress清理onChange之前的输入,而不会产生“副作用”。

代码沙箱:https://codesandbox.io/s/9jlm59n52r

import React from "react";
import ReactDOM from "react-dom";

class Input extends React.Component {
  state = { value: this.props.value };

  handleKeyPress = e => {
    let keyPressed = e.key;

    if (/[0-9]/.test(keyPressed)) {
      e.preventDefault();
    }
  };

  handleChange = e => {
    this.setState({ value: e.target.value });
  };

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

ReactDOM.render(
  <Input value="type something here" />,
  document.getElementById("root")
);

编辑:

清理粘贴上的输入

handlePaste = e => {
  let pastedText = e.clipboardData.getData("text/plain");

  if (/[0-9]/.test(pastedText)) {
    e.preventDefault();
  }
}

...

  <input
    ...
    onPaste={this.handlePaste}
    ...
  />