reactjs - 有没有办法在 React JS 中的按钮 Click 上调用组件?
问题描述
我正在制作老虎机游戏,我想在按钮单击时显示表情符号,但按钮无法正常工作。我还尝试通过传递带有道具的表情符号来在按钮单击时显示组件,但这也不起作用。
import React,{Component} from 'react';
import '../App.css';
import SpGame from './SpGame.js';
const allowedEmoji=['','','','','','','','','']
var x=allowedEmoji[Math.floor(Math.random() * allowedEmoji.length)];
var y=allowedEmoji[Math.floor(Math.random() * allowedEmoji.length)];
var z=allowedEmoji[Math.floor(Math.random() * allowedEmoji.length)];
class Sgame extends Component {
constructor(props) {
super(props);
this.sayHello = this.sayHello.bind(this);
}
sayHello() {
if(x === y && y === z)
{
return (
<div className="background">
<hr/>
<h3>{x} {y} {z}</h3>
<p>Lucky! Match Found</p>
<hr/>
</div>
);
}
else
{
return (
<div className="background">
<hr/>
<h3>{x} {y} {z}</h3>
<p>UnLucky! Match Not Found</p>
<hr/>
</div>
);
}
}
render(){
return (
<div>
<div className="background">
<div className="header">
<h3> Slot Machine Game </h3>
<button onClick={this.sayHello}>Try Again</button>
{this.sayHello}
</div>
</div>
</div>
)
}
}
export default Sgame;
解决方案
这里有两种可能性。
条件渲染
将组件设置为显示为状态变量
在第一种情况下,您需要添加组件 i 行的render
方法,如下所示:Sgame
return (
...
{this.state.clicked ? <div> the html you want to show in case button is clicked </div> : null}
...
)
你的sayHello
实施将是:
sayHello() {
this.setState({ clicked:true })
}
但一定要在你的构造函数中添加状态变量:
constructor(props){
super(props)
this.sayHello = this.sayHello.bind(this);
clicked = null;
}
在这种情况下,一旦单击按钮,setState()
将调用函数并更新状态,因此将重新渲染组件,变量clicked
将为 true 并显示三元运算符中的组件。请注意,要触发 DOM 中的更改,您需要使用 setState 函数通过 react lyfecycle。
另一种可能性是设置这样的状态变量:
constructor(props){
super(props)
this.sayHello = this.sayHello.bind(this);
this.state = { componentToShowAfterClick : null };
}
在sGame
你放的渲染方法中{this.state.componentToShowAfterClick}
。在第一次渲染时它将为空。然后你修改你是sayHello
,删除return
和调用setState(this.state.componentToShowAfterClick : <div>you're custom html here</div>)
推荐阅读
- sql - 查询以选择适当的行并计算经过的时间
- java - 可以在 Java 中使用枚举作为 List 元素吗?
- php - Laravel Guzzle 在 Get() 方法中返回空白响应
- python - 如何在python中迭代非常大的数据框?
- amazon-web-services - AWS 上的 HashiCorp Vault 快速入门:如何从 localhost 通过堡垒连接到 Vault?
- java - 如何使用 Jackson 序列化带有嵌套有效负载的 Flux 样式操作?
- php - 如何在 amcharts 中的图表条内显示值
- java - RESTEasy 与 Guice InstantiationError 在部署(App Engine 本地)
- rate-limiting - 生成资源的球童速率限制
- javascript - 如何在 html 标签中获取内容,包括在 javascript 中使用正则表达式的标签?