React,如何检测在表单字段中键入的特定字符

React, How to detect a specific character is typed inside a form field

我有一个 "input field" 组件。如果在输入字段中键入“#”字符,我需要显示警报。有什么办法,我们可以确定字符是键入的。

export default class MyComponent extends Component {

    constructor(props) {
        super(props);
        this.state = {};
    }

    handleKeyPress(e) {
        // show an alert if "#" character is pressed
    }

    render() {
        return (
            <input onChange={this.handleKeyPress}>
        )
    }
}

编辑

我想在用户输入“#”字符后立即显示警报。之后,他可以在没有警报提示的情况下继续输入任何字符。如果用户在输入字段中键入另一个“#”,则应再次出现警报。

如有任何想法,我们将不胜感激。

export default class DayView extends Component {

  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };

    // Bind `this`
    this.handleKeyPress = this.handleKeyPress.bind(this);
  }

  handleKeyPress(e) {
    // Get input value
    var value = e.target.value;
    // User has already typed a #
    var hasSymbol = !!value.substring(0, value.length - 1).match(/\#/);

    // Check if last character is a #
    if (value[value.length - 2] === '#') {
      alert('There is a # symbol');
    }

    // Check if this last character is a #
    // and the value already has one
    if (hasSymbol && value[value.length - 1] === '#') {
      alert('There is an other # symbol');
    }

    // Set state
    this.setState({ value });
  }

  render() {
    return (
      <input onChange={this.handleKeyPress} value={this.state.value}>
    )
  }
}

使用 event.target.value 获取值并获取最新字符使用 e.target.value[e.target.value.length - 1] 并检查是否有 #.

希望对您有所帮助!

class DayView extends React.Component {

    constructor(props) {
        super(props);
        this.state = {};
    }

    handleKeyPress(e) {
      if( e.target.value[e.target.value.length - 1] === '#' )
        setTimeout(()=> alert('Got #'), 200)
        // show an alert if "#" character is pressed
    }

    render() {
        return (
            <input onChange={this.handleKeyPress}/>
        )
    }
}

ReactDOM.render(<DayView/>, document.getElementById('app'))
<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>
<div id="app"></div>

keyUp 在这种情况下比 keyPress & change 更合适;

希望对您有所帮助!

class DayView extends React.Component {

    constructor(props) {
        super(props);
        this.state = {};
        this.handleKeyUp= this.handleKeyUp.bind(this);
    }

    handleKeyUp(e) {
     
       this.refs.atom.value.endsWith('#')  && setTimeout(()=> alert('Got #'), 200) // show an alert if "#" character is pressed
    }

    render() {
        return (
            <input ref="atom" onKeyUp={this.handleKeyUp}/>
        )
    }
}

ReactDOM.render(<DayView/>, document.getElementById('app'))
<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>
<div id="app"></div>