Javascript 如何在React jsx中使用innerHTML呈现组件

Javascript 如何在React jsx中使用innerHTML呈现组件,javascript,html,css,reactjs,jsx,Javascript,Html,Css,Reactjs,Jsx,我目前正在编写在两个视图(图形和列表)之间切换的功能。二是视图容器类的名称 toggleGraphView(){ consttwo=document.getElementsByClassName('two')[0]; two.innerHTML='图形视图!' } toggleListView(){ consttwo=document.getElementsByClassName('two')[0]; two.innerHTML=“” }我不是ReactJS专家,但我认为您应该返回正确的内容,

我目前正在编写在两个视图(图形和列表)之间切换的功能。二是视图容器类的名称

toggleGraphView(){
consttwo=document.getElementsByClassName('two')[0];
two.innerHTML='图形视图!'
}
toggleListView(){
consttwo=document.getElementsByClassName('two')[0];
two.innerHTML=“”

}
我不是ReactJS专家,但我认为您应该返回正确的内容,而不是试图通过JS进行更改:

  toggleView() {
      if (this.isGraphView()) {
          return <span>Graph View!</span>;
      } else {
          return <ShotLog shotLog={this.state.shotLog}/>
      }
  }
toggleView(){
if(this.isGraphView()){
返回图形视图!;
}否则{
返回
}
}

您不能通过将组件放入字符串来创建React组件,使用JSX,您的代码可以缩短为以下内容:

this.state.showGraph ? <span>Graph View!</span> : <ShotLog shotLog={this.state.shotLog} />

结合@Justinas的答案,您可以尝试执行条件渲染,而不是使用纯JS。您可以尝试以下方法:

MyComponent extends React.Component {
  constructor(props) {
      super(props);
      this.state = {currView: 'graph'};
  }

  handleToggle() {
      if (this.state.currView === 'graph') {
          this.setState({currView: 'otherView'});
      } else {
          this.setState({currView: 'graph'});
      }
  }

  render() {
      if(this.state.currView === 'graph') {
          // render your 'graph' view
      } else {
          // render some other view
      }
   }
}
组件状态的更改将导致重新渲染,因此它应该完全更改以前存在的内容。只需确保您拥有可以切换或更新状态的功能:)


另外,如果我在react相关语法中犯了一些错误,请原谅。现在没有IDE lol

您可以使用react方式切换视图,而不是尝试使用document.getElementsByClassName直接访问dom。你可以参考我下面的例子

class TestComponent 
{

constructor(props) {
  super(props); 
  this.state = {
    view: 'list', 
    shotLog: someVal
  }

  handleToggle() {
     const modifiedView= this.state.view == 'graph'? 'list': 'graph'; 
     this.setState(() => {
      return {view: modifiedView}; 
     });

  }

}


render() {
     const {view, shotLog} = this.state;
     <div> 
       <button onClick={this.handleToggle}> Toggle </button> 

       {view == 'graph'} && <span> Graph View! </span> 
       {view == 'list'} && <ShotLog shotLog={shotLog} /> 


     </div>
}



}
类测试组件
{
建造师(道具){
超级(道具);
此.state={
查看:“列表”,
shotLog:someVal
}
手语{
const modifiedView=this.state.view=='graph'?'list':'graph';
此.setState(()=>{
返回{view:modifiedView};
});
}
}
render(){
const{view,shotLog}=this.state;
切换
{view=='graph'}&&graph view!
{view=='list'}&&
}
}

非常感谢!这正是我需要帮助的地方。干杯,我能帮忙的小伙子:)