按下按钮时,在ReactJS的页面上添加文本

时间:2019-10-01 03:21:33

标签: javascript reactjs

我想使用JSX在addInfo函数中显示文本到我的页面!请分享建议。不要只是给我答案;解释解决问题的步骤。预先谢谢你。

let view = ''

const addInfo = () => {

  view = 'Hi my name is'

  showDetails()

}

const showDetails = () => {

  const view = ( 
  <div>
    <h1> Move on </h1>
    <button onClick = { addInfo }> show details </button>
    <p> {view} </p>
  </div>
  )

  ReactDOM.render(view, document.getElementById('root'))

}

showDetails()
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<span id="root"></span>

1 个答案:

答案 0 :(得分:0)

唯一的问题是,您要显示的文本和要呈现的元素都使用名称view。要解决此问题,只需更改其中之一的名称即可。

let view = ''

const addInfo = () => {

  view = 'Hi my name is'

  showDetails()

}

const showDetails = () => {

  const renderView = ( /* Changed this variable name */
  <div>
    <h1> Move on </h1>
    <button onClick = { addInfo }> show details </button>
    <p> {view} </p>
  </div>
  )

  ReactDOM.render(renderView, document.getElementById('root')) /* Changed here, too */

}

showDetails()
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>