如何在React jsx中使用innerHTML渲染组件

时间:2018-12-17 08:34:27

标签: javascript html css reactjs jsx

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

  toggleGraphView() {
    const two = document.getElementsByClassName('two')[0];
    two.innerHTML = '<span>Graph View!</span>'
  }

  toggleListView() {
    const two = document.getElementsByClassName('two')[0];
    two.innerHTML = "<ShotLog shotLog={this.state.shotLog}/>"
  }

该组件可以很好地切换到图形视图文本(“图形视图!”),但是当我尝试切换回列表视图时,我什么也没得到。触发toggleListView之后,在chrome工具中,两个容器包含<shotlog shotlog="{this.state.shotLog}/"></shotlog>。我需要它看起来像<ShotLog shotLog={this.state.shotLog}/>才能正确传递道具。

我不确定多余的报价来自哪里。有什么想法吗?

4 个答案:

答案 0 :(得分:1)

我不是ReactJS的专家,但我认为您应该返回适​​当的内容,而不是尝试通过JS进行更改:

  toggleView() {
      if (this.isGraphView()) {
          return <span>Graph View!</span>;
      } else {
          return <ShotLog shotLog={this.state.shotLog}/>
      }
  }

答案 1 :(得分:1)

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

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

使用三元条件,您可以根据变量showGraph

决定要呈现的内容

showGraph将存储在组件的状态中,可通过this.state访问,当您想更改状态中某物的值时,必须调用setState,这将使您的组件重新呈现屏幕上的所有内容,并向您显示所需的内容

工作示例:

class ShotLog extends React.Component {
  render() {
    return <div>Hi I'm a ShotLog</div>
  }
}


class App extends React.Component {
  constructor(props){
    super(props)
    this.state = { showGraph: true }
  }
  handleClick = ev => {
    this.setState({ showGraph: !this.state.showGraph })
  }
  render() {
    return (
      <div>
        {this.state.showGraph ? 
          <span>Graph View!</span> 
          : 
          <ShotLog />}
        <button onClick={this.handleClick}>Switch me !</button>
      </div>
    )
  }
}
    
ReactDOM.render(
  <App/>,
  document.getElementById('react')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>
<div id="react"></div>

您可以在以下官方文档中找到JSX的基础知识:https://reactjs.org/docs/introducing-jsx.html

您可以在此处了解有关组件状态的更多信息:https://reactjs.org/docs/state-and-lifecycle.html

答案 2 :(得分:1)

结合@Justinas的答案,您可以尝试执行条件渲染,而不是使用纯JS进行。您可以尝试这样的事情:

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        server_name  _;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        root /usr/share/nginx/html;

        location ^~ /core/ {
            proxy_pass http://my-named-backend:8080/;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Port $server_port;
            proxy_set_header X-Real-IP $remote_addr;
        }

        location / {
            # Nothing to put here since the dist/ files are
            # /usr/share/nginx/html is automatically served.
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}

对组件状态的更改将导致重新渲染,因此它应该完全更改以前存在的任何内容。只要确保您有可以切换或更新状态的东西即可:)

P.S。抱歉,如果我在react相关语法中犯了一些错误。现在没有IDE大声笑

答案 3 :(得分:1)

您可以使用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>
}



}