中断在ReactJS中输入ContentEditable Div上的键

时间:2016-05-20 20:47:29

标签: javascript reactjs javascript-events contenteditable

我想中断Enter key并阻止它将html代码注入ContentEditable div。我当前的代码不起作用,因为它不会中断Enter key。但是,如果我键入,请按Enter键,然后再次键入,它将删除内部html元素。但是,这仍然不是我想要的。我希望元素不要进入ContentEditable div,以便在按Enter键时开始,而不是将它们删除。

我基本上将其用作input that scales with its content。如果有更好的方法,请告诉我!

import ReactDOM from 'react-dom'

export default class MyInput extends React.Component {    
  componentWillReceiveProps(nextProps) {
    this.setState({value: nextProps.html});
  }

  shouldComponentUpdate(nextProps){
    return nextProps.html !== ReactDOM.findDOMNode(this).innerHTML;
  }

  componentDidUpdate() {
    if ( this.htmlEl && this.props.html !== this.htmlEl.innerHTML ) {
     this.htmlEl.innerHTML = this.props.html;
    }
  }

  emitChange(){
    var html = ReactDOM.findDOMNode(this).innerHTML;

    // regex to remove tags created after pressing enter
    value = value.replace(/<div>/g, '');
    value = value.replace(/<\/div>/g, '');
    value = value.replace(/<br>/g, '');

    if (this.props.onChange && html !== this.lastHtml) {
      this.props.onChange(html);
    }
    this.lastHtml = html;
    this.forceUpdate();
  }

  render() {
    var html = this.state.value;
    return (
      <div
        dangerouslySetInnerHTML={{__html: html}}
        onInput={this.emitChange.bind(this)}
        onBlur={this.emitChange.bind(this)}
        contentEditable
      ></div>
    )
  }
};

2 个答案:

答案 0 :(得分:4)

  //  function handler inside class declaration
  keyPress(event) {
    if(event.charCode == 13) {
      event.preventDefault()
    }
  }

  //  in render function
  <div
    dangerouslySetInnerHTML={{__html: html}}
    onInput={this.emitChange.bind(this)}
    onBlur={this.emitChange.bind(this)}
    onKeyPress={this.keyPress.bind(this)}
    contentEditable
  ></div>

答案 1 :(得分:2)

使用键盘事件绑定div,然后:

var keyCode = event.which || event.keyCode;
keyCode === 13 && event.preventDefault();