在 ContentEditable 中输入时,每个新字符都会导致元素模糊并可能重新渲染。当删除 ContentEditable 的父元素 Highlight 时,它会保持焦点,但不幸的是我需要语法突出显示功能。我尝试按照类似问题中的建议向 ContentEditable 添加 key ,但这不起作用。任何有关如何解决此问题的想法都会有很大帮助。谢谢!
主要组件
var Stdin = React.createClass({
getInitialState: function(){
return {html: ""};
},
handleChange: function(evt){
console.log('evt: ', $.extend({}, evt));
this.setState({html: evt.nativeEvent.target.textContent});
evt.preventDefault();
return false;
},
copyContent: function() {
$("#fake-input").val($("#real-input").html());
return true;
},
render: function () {
return (
<div id="stdin">
<div className="arrow-right"></div>
<form action="#" onSubmit={this.copyContent}>
<input type="text" id="real-input"></input>
<Highlight className='css'>
<ContentEditable key="fake-input" id="fake-input" html={this.state.html} onChange={this.handleChange}/>
</Highlight>
<input type="submit"/>
</form>
</div>
);
}
});
突出显示组件
var Highlight = React.createClass({
displayName: 'Highlight',
getDefaultProps: function getDefaultProps() {
return {
innerHTML: false,
className: ''
};
},
componentDidMount: function componentDidMount() {
this.highlightCode();
},
componentDidUpdate: function componentDidUpdate() {
this.highlightCode();
},
highlightCode: function highlightCode() {
var domNode = this.getDOMNode();
var nodes = domNode.querySelectorAll('pre code');
if (nodes.length > 0) {
for (var i = 0; i < nodes.length; i = i + 1) {
hljs.highlightBlock(nodes[i]);
}
}
return false;
},
render: function render() {
if (this.props.innerHTML) {
console.log("hey1");
return React.createElement('div', { dangerouslySetInnerHTML: { __html: this.props.children }, className: this.props.className || null });
} else {
console.log(this.props.children);
return React.createElement(
'pre',
null,
React.createElement(
'code',
{ className: this.props.className, key: 'code-key' },
this.props.children
)
);
}
}
});
内容可编辑组件
var ContentEditable = React.createClass({
render: function(){
return React.createElement('div', { onInput: this.emitChange, onBlur: this.emitChange, contentEditable: true, dangerouslySetInnerHTML: {__html: this.props.html}, id: this.props.id, className: this.props.className});
},
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(evt){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
evt.target = { value: html };
this.props.onChange(evt);
}
this.lastHtml = html;
}
});
最佳答案
我也有同样的问题。我的第一个解决方案是从渲染方法中删除所有 React.createX()
。在 React 中创建元素会导致重新渲染。
我仍然遇到问题,但这也许可以解决您的问题。
关于javascript - React editablecontent div 失去了对打字/重新渲染的关注,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32174940/