NVI*_*NVI 95 javascript dom contenteditable reactjs
如何收听contentEditable基于更改事件的控件?
var Number = React.createClass({
render: function() {
return <div>
<span contentEditable={true} onChange={this.onChange}>
{this.state.value}
</span>
=
{this.state.value}
</div>;
},
onChange: function(v) {
// Doesn't fire :(
console.log('changed', v);
},
getInitialState: function() {
return {value: '123'}
}
});
React.renderComponent(<Number />, document.body);
Run Code Online (Sandbox Code Playgroud)
Bri*_*and 71
编辑:请参阅Sebastien Lorber的答案,该答案修复了我的实施中的错误.
使用onInput事件,以及可选的onBlur作为后备.您可能希望保存以前的内容以防止发送额外的事件.
我个人认为这是我的渲染功能.
var handleChange = function(event){
this.setState({html: event.target.value});
}.bind(this);
return (<ContentEditable html={this.state.html} onChange={handleChange} />);
Run Code Online (Sandbox Code Playgroud)
哪个使用这个简单的包装在contentEditable周围.
var ContentEditable = React.createClass({
render: function(){
return <div
onInput={this.emitChange}
onBlur={this.emitChange}
contentEditable
dangerouslySetInnerHTML={{__html: this.props.html}}></div>;
},
shouldComponentUpdate: function(nextProps){
return nextProps.html !== this.getDOMNode().innerHTML;
},
emitChange: function(){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
this.props.onChange({
target: {
value: html
}
});
}
this.lastHtml = html;
}
});
Run Code Online (Sandbox Code Playgroud)
Seb*_*ber 61
编辑2015
有人用我的解决方案在NPM上做了一个项目:https://github.com/lovasoa/react-contenteditable
编辑06/2016:我刚刚遇到了一个新问题,当浏览器试图"重新格式化"你刚给他的html时,会出现一个新的问题,导致组件总是重新渲染.看到
编辑07/2016:这是我的生产内容可编辑的实现.它有一些react-contenteditable您可能想要的其他选项,包括:
在我遇到新问题之前,FakeRainBrigand的解决方案对我来说已经有一段时间了.ContentEditables很痛苦,并不容易处理React ......
这个JSFiddle演示了这个问题.
如您所见,当您键入一些字符并单击时Clear,内容不会被清除.这是因为我们尝试将contenteditable重置为最后一个已知的虚拟dom值.
所以似乎:
shouldComponentUpdate防止插入位置跳跃shouldComponentUpdate这种方式,则不能依赖React的VDOM差分算法.因此,您需要一个额外的行,以便每当shouldComponentUpdate返回yes时,您确定DOM内容实际更新.
所以这里的版本增加了一个componentDidUpdate并成为:
var ContentEditable = React.createClass({
render: function(){
return <div id="contenteditable"
onInput={this.emitChange}
onBlur={this.emitChange}
contentEditable
dangerouslySetInnerHTML={{__html: this.props.html}}></div>;
},
shouldComponentUpdate: function(nextProps){
return nextProps.html !== this.getDOMNode().innerHTML;
},
componentDidUpdate: function() {
if ( this.props.html !== this.getDOMNode().innerHTML ) {
this.getDOMNode().innerHTML = this.props.html;
}
},
emitChange: function(){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
this.props.onChange({
target: {
value: html
}
});
}
this.lastHtml = html;
}
});
Run Code Online (Sandbox Code Playgroud)
虚拟dom保持过时,它可能不是最有效的代码,但至少它确实有效:) 我的错误已解决
细节:
1)如果你把shouldComponentUpdate放在以避免插入符号跳转,那么contenteditable永远不会重新渲染(至少在击键时)
2)如果组件永远不会在击键时重新渲染,那么React会保留一个过时的虚拟dom.
3)如果React在其虚拟dom树中保留了一个过时版本的contenteditable,那么如果你试图将contenteditable重置为虚拟dom中过时的值,那么在虚拟dom diff期间,React会计算出没有变化适用于DOM!
这主要发生在:
Sai*_*ent 23
由于编辑完成后元素的焦点总是丢失,您可以简单地使用 onBlur 钩子。
<div onBlur={(e)=>{console.log(e.currentTarget.textContent)}} contentEditable suppressContentEditableWarning={true}>
<p>Lorem ipsum dolor.</p>
</div>
Run Code Online (Sandbox Code Playgroud)
Dan*_*mov 15
这可能不是你正在寻找的答案,但是我自己也在努力解决这个问题并提出建议的答案,我决定让它不受控制.
当editableprop是false,我text按原样使用prop,但是当它被用时true,我切换到编辑模式,其中text没有任何效果(但至少浏览器不会吓坏).在此期间onChange由控件触发.最后,当我改editable回时false,它用传入的任何内容填充HTML text:
/** @jsx React.DOM */
'use strict';
var React = require('react'),
escapeTextForBrowser = require('react/lib/escapeTextForBrowser'),
{ PropTypes } = React;
var UncontrolledContentEditable = React.createClass({
propTypes: {
component: PropTypes.func,
onChange: PropTypes.func.isRequired,
text: PropTypes.string,
placeholder: PropTypes.string,
editable: PropTypes.bool
},
getDefaultProps() {
return {
component: React.DOM.div,
editable: false
};
},
getInitialState() {
return {
initialText: this.props.text
};
},
componentWillReceiveProps(nextProps) {
if (nextProps.editable && !this.props.editable) {
this.setState({
initialText: nextProps.text
});
}
},
componentWillUpdate(nextProps) {
if (!nextProps.editable && this.props.editable) {
this.getDOMNode().innerHTML = escapeTextForBrowser(this.state.initialText);
}
},
render() {
var html = escapeTextForBrowser(this.props.editable ?
this.state.initialText :
this.props.text
);
return (
<this.props.component onInput={this.handleChange}
onBlur={this.handleChange}
contentEditable={this.props.editable}
dangerouslySetInnerHTML={{__html: html}} />
);
},
handleChange(e) {
if (!e.target.textContent.trim().length) {
e.target.innerHTML = '';
}
this.props.onChange(e);
}
});
module.exports = UncontrolledContentEditable;
Run Code Online (Sandbox Code Playgroud)
这是最适合我的最简单的解决方案。
<div
contentEditable='true'
onInput={e => console.log('Text inside div', e.currentTarget.textContent)}
>
Text inside div
</div>
Run Code Online (Sandbox Code Playgroud)
我建议使用一个mutationObserver来做到这一点。它为您提供了更多控制权。它还为您提供有关浏览器如何解释所有按键的更多详细信息。
在TypeScript中
import * as React from 'react';
export default class Editor extends React.Component {
private _root: HTMLDivElement; // Ref to the editable div
private _mutationObserver: MutationObserver; // Modifications observer
private _innerTextBuffer: string; // Stores the last printed value
public componentDidMount() {
this._root.contentEditable = "true";
this._mutationObserver = new MutationObserver(this.onContentChange);
this._mutationObserver.observe(this._root, {
childList: true, // To check for new lines
subtree: true, // To check for nested elements
characterData: true // To check for text modifications
});
}
public render() {
return (
<div ref={this.onRootRef}>
Modify the text here ...
</div>
);
}
private onContentChange: MutationCallback = (mutations: MutationRecord[]) => {
mutations.forEach(() => {
// Get the text from the editable div
// (Use innerHTML to get the HTML)
const {innerText} = this._root;
// Content changed will be triggered several times for one key stroke
if (!this._innerTextBuffer || this._innerTextBuffer !== innerText) {
console.log(innerText); // Call this.setState or this.props.onChange here
this._innerTextBuffer = innerText;
}
});
}
private onRootRef = (elt: HTMLDivElement) => {
this._root = elt;
}
}
Run Code Online (Sandbox Code Playgroud)