Javascript 在React中的Switch语句中使用document.getElementId
我希望根据“#pairName”中的内部文本显示特定的图形,但似乎无法理解为什么这不起作用。我的完整代码可以在:,以更好地理解代码Javascript 在React中的Switch语句中使用document.getElementId,javascript,reactjs,switch-statement,jsx,dom-manipulation,Javascript,Reactjs,Switch Statement,Jsx,Dom Manipulation,我希望根据“#pairName”中的内部文本显示特定的图形,但似乎无法理解为什么这不起作用。我的完整代码可以在:,以更好地理解代码 displayGraph = () => { switch(document.getElementById('pairName').innerText){ case 'USD/EUR': return <Graph selectedBase = {this.state.selectedBase}
displayGraph = () => {
switch(document.getElementById('pairName').innerText){
case 'USD/EUR':
return <Graph selectedBase = {this.state.selectedBase} defaultBase={"EUR"} today ={this.state.EURfirstDateValues} lastWeek = {this.state.EURfifthDateValues}/>;
case 'USD/CAD':
return <Graph selectedBase = {this.state.selectedBase} defaultBase={"CAD"} today = {this.state.CADfirstDateValues} lastWeek = {this.state.CADfifthDateValues}/>;
case 'USD/NZD':
return <Graph selectedBase = {this.state.selectedBase} defaultBase={"NZD"} today = {this.state.NZDfirstDateValues} lastWeek = {this.state.NZDfifthDateValues}/>;
case 'USD/AUD':
return <Graph selectedBase = {this.state.selectedBase} defaultBase={"AUD"} today = {this.state.AUDfirstDateValues} lastWeek = {this.state.AUDfifthDateValues}/>;
case 'USD/JPY':
return <Graph selectedBase = {this.state.selectedBase} defaultBase={"JPY"} today = {this.state.JPYfirstDateValues} lastWeek = {this.state.JPYfifthDateValues}/>;
}
}
displayGraph=()=>{
开关(document.getElementById('pairName').innerText){
“美元/欧元”案例:
返回;
“美元/加元”案例:
返回;
“美元/新西兰元”案例:
返回;
“美元/澳元”案例:
返回;
“美元/日元”案例:
返回;
}
}
美元/欧元
{/*目标:选择正确对时显示图形*/}
{this.displayGraph}
您应该有一个默认值
案例。还有,你到底得到了什么?我会在开关之前添加console.log(
document.getElementById('pairName').innerText)`以确保访问的数据正确。另外,使用textContent
而不是.innerText
。您不应该在React中直接进行DOM操作。将值存储在状态中。另外,displayGraph
是一个函数,因此需要调用它:{this.displayGraph()}
<h2 id="pairName">USD/EUR</h2>
{/* GOAL: show graphs when correct pairs are selected */}
{this.displayGraph}