首页 > 解决方案 > 如何在 React jsx 中使用 innerHTML 渲染组件

问题描述

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

  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}/>才能正确传递道具。

我不确定额外的报价是从哪里来的。有任何想法吗?

标签: javascripthtmlcssreactjsjsx

解决方案


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

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


推荐阅读