我正在学习 ReactJS 和 Node/Express 生态系统(对我来说是早期)。我有一个基本的 ReactJS 文件,包括组件定义和渲染调用。它本身按预期工作。为了快速/轻松地进行调试,昨天我在客户端代码中进行了以下更改:
// Added HTML id to body tag, no other changes whatsoever to DOM/HTML
<body id='body'>...</body>
// In client code, added:
document.getElementById('body').innerHTML += xhr.responseText;
xhr
是一个经过验证的函数式 xmlHttpRequest()。我发出请求,得到响应,然后它按预期呈现给正文。然而,这stops所有 ReactJS 组件都会监听其按钮并按定义触发其处理程序。没有控制台反馈或其他迹象表明有任何问题,ReactJS 只是按预期进行第一次渲染,然后默默地停止响应。
如果我注释掉单行document.getEle...
然后一切又开始工作了,包括 React 和xhr
itself.
我知道在 ReactJS 中,范例不是以这种方式修改 DOM,但我不明白为什么这一行会破坏所有 ReactJS 功能。对于上下文,这是我的代码的一部分:
无论是否注释掉 document.getEle...,该组件似乎都很好。
// Hello World component: manage cookies and display a simple prop
var HelloWorldComponent = React.createClass({
componentWillMount: function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if( xhr.readyState == 4 && xhr.status == 200 ) {
// NOTE: this `console.log` gives expected result regardless
console.log('Performed initial cookie check. Got response: ' + xhr.responseText);
// document.getElementById('body').innerHTML += '<div>'+xhr.responseText+'</div>';
}
else {
console.log('Tried initial cookie check. Got HTTP response status: ' + xhr.status);
}
}
xhr.open('POST', '/cookieCheck');
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.send();
},
render: function() {
return (
<h1 id='italic-id' className='red-class'>Hello, {this.props.name}!</h1>
);
}
});
该组件损坏unless document.getEle...
被注释掉了,否则它工作得很好。
// State component to display simple state
var StateComponent = React.createClass({
// ReactJS Event: this fails with `document.getEle...` appearing elsewhere in the code
incrementCount: function() {
this.setState({
count: this.state.count + 1
});
},
getInitialState: function() {
return {
count: 0
}
},
render: function() {
return (
<div className='increment-component'>
<h3 className='red-class'>Count: {this.state.count}.</h3>
<button onClick={this.incrementCount}>Boing!</button>
</div>
);
}
});
以下是我渲染组件的方式:
ReactDOM.render(
<StateComponent/>,
document.getElementById('state-point')
);
// similar calls for other components as needed
对于它的价值,我已经尝试过document.getEle...
作为第一个 JS 触发,作为最后一个 JS 触发,以及您现在看到的它作为 ReactJS 组件的一部分。无论我将其放在代码中的哪个位置,结果都是相同的。