【问题标题】:React JS getting started issueReact JS 入门问题
【发布时间】:2020-03-22 11:46:29
【问题描述】:

您好,我被这个问题困住了,我刚刚开始使用 react js。它是 HOME js 组件 单击按钮时,我想显示一些文本(当标志为真时),否则它不应该显示任何内容。

import React from 'react';

export default class Home extends React.Component{

 constructor(props)
 {
    super(props);
    this.state = {flag: false}
    this.showMe = this.showMe.bind(this);

 }
showMe()
 {
   this.state.flag ? ((<div> show this when flag is true </div>) : null)
 }


render()
{

    return(
        <div>
    <h1>Welcome to the Tornadoes Website {this.state.flag}</h1>
    <button type="button" onClick={this.showMe}>Click me </button>


  </div>);
}

}

控制台错误:

16:2:  Parsing error: Unexpected token, expected ":"

  14 |  {
  15 |    this.state.flag ? ((<div> show this when flag is true</div>) : null)
> 16 |  }
     |  ^
  17 |
  18 |
  19 | render()

【问题讨论】:

  • 你有不平衡的括号,这是错误告诉你的。它看起来像一个简单的错字。
  • 错字修正后,您得到的答案只是解释了另一个热门问题if-else statement inside jsx: ReactJS

标签: javascript html reactjs frontend


【解决方案1】:

您希望showMe 处理程序仅更改状态。

showMe 的返回正文应该在 render 函数中返回,因为您正在返回 JSX/HTML。

showMe() { 
  this.setState({flag: !this.state.flag})
}

render()
{

    return(
    <div>
      <h1>Welcome to the Tornadoes Website {this.state.flag}</h1>
      <button type="button" onClick={this.showMe}>Click me </button>
      {this.state.flag ? ((<div> show this when flag is true </div>) : null)}

    </div>
   );
}

【讨论】:

  • 我试过你的改变没有用。当我单击按钮时,如果标志为真,那么它应该显示一些文本,否则什么也没有。感谢您的快速响应。
  • 正确。我编辑了showMe 方法来改变状态
  • 我做了,但它说我需要等待 5 分钟 :)
猜你喜欢
  • 2017-02-24
  • 1970-01-01
  • 2020-07-29
  • 1970-01-01
  • 2021-12-18
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多