首页 > 解决方案 > 有没有办法在 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;

标签: reactjs

解决方案


这里有两种可能性。

  1. 条件渲染

  2. 将组件设置为显示为状态变量

在第一种情况下,您需要添加组件 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>)


推荐阅读