Javascript 快速入门问题
嗨,我被这个问题困住了,我刚刚开始使用react js。它是主js组件 当按钮被点击时,我想显示一些文本(当标志为真时),否则它应该什么也不显示Javascript 快速入门问题,javascript,html,reactjs,frontend,Javascript,Html,Reactjs,Frontend,嗨,我被这个问题困住了,我刚刚开始使用react js。它是主js组件 当按钮被点击时,我想显示一些文本(当标志为真时),否则它应该什么也不显示 import React from 'react'; export default class Home extends React.Component{ constructor(props) { super(props); this.state = {flag: false} this.showMe = this.sh
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>);
}
}
从“React”导入React;
导出默认类Home扩展React.Component{
建造师(道具)
{
超级(道具);
this.state={flag:false}
this.showMe=this.showMe.bind(this);
}
showMe()
{
this.state.flag?((当标志为true时显示):null)
}
render()
{
返回(
欢迎访问龙卷风网站{this.state.flag}
点击我
);
}
}
控制台上的错误:
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()
16:2:分析错误:意外标记,应为“:”
14 | {
15 | this.state.flag?((当flag为true时显示):null)
> 16 | }
| ^
17 |
18 |
19 | render()
您希望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(){
this.setState({flag:!this.state.flag})
}
render()
{
返回(
欢迎访问龙卷风网站{this.state.flag}
点击我
{this.state.flag?((当flag为true时显示):null)}
);
}
我试过了,但你的更改不起作用。当我点击按钮,如果标志是真的,那么它应该显示一些文本,其他什么都没有。谢谢你的快速回复。正确。我编辑了showMe
方法来更改状态,但它说我需要等待5分钟:)错误告诉您,括号不平衡。它看起来像一个简单的打字错误。一旦拼写错误被纠正,你得到的答案就是解释另一个流行问题中的内容