Reactjs скрывает и отображает начальный экран, используя хуки вместо классов

#javascript #reactjs #state #react-props

#javascript #reactjs #состояние #react-props

Вопрос:

У меня есть некоторый код, который отображает начальный экран, но когда я нажимаю кнопку «Пуск», он выдает ошибку: «this.props.clickevent» не является функцией. Как я могу повторно удалить начальный экран после нажатия кнопки «Пуск», используя перехваты вместо классов? В принципе, мне нужно сделать переменную GameOn true на рабочем столе, чтобы она устанавливала экран в скрытое положение, но не уверен, как это сделать с помощью перехватов.

Вот код, с которым я работал для начального экрана:

 import React from 'react';
import './homescreen.css';
var isGameOn = false;
class Homescreen extends React.Component{
   constructor(){
      super();
      this.clickMe = this.clickMe.bind(this);
}
  clickMe(){
//call parent function that manages state
 this.props.clickEvent();

   }
         render(){
       return (
          <div className={isGameOn ? "homescreen homescreen--visible" : "homescreen homescreen--hidden"}>
        <div className="homescreen__box">
          <h1 className="homescreen__title">Spaceamp;nbsp;  Matcher</h1>
          <div className="homescreen__stats">
            Games Played: <strong className="homescreen__number" >{this.props.gamesWon}</strong>
          </div>
          <button className="homescreen__shuffle-button " onClick={this.clickMe} >Start!</button>
           </div>
          </div>
         )
     }
}

export default Homescreen;
export {isGameOn}
  

И вот часть приложения, которое отображает мой домашний экран:

 import Homescreen, {isGameOn} from './homescreen'
var gamesPlayed = 0;
export default function App() {

function startGame(){
    gamesPlayed =1;
    isGameOn = true;
    console.log(isGameOn);
  }
  return (

    <Homescreen gameOver = {isGameOn} gamesWon = {gamesPlayed} clickEvent = {startGame}/>
 }
  

Вот css:

 .homescreen{
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;

  z-index: 4;
}

.homescreen--visible{
 animation-name: pop-in;
 animation-duration: .75s;
 animation-fill-mode: forwards;
}
.homescreen--hidden{
  //display: none;
 animation-name: pop-away;
 animation-duration: .75s;
 animation-fill-mode: forwards;
}

.homescreen__box{
  width: 90%;
  background-color: red;
  background: linear-gradient(to bottom, rgba(255,51,0,1) 0%,rgba(153,0,0,1) 100%);
  padding: 20px;
  text-align: center;
  border-radius: 30em;
  border: 6px solid orange;
}

.homescreen__title{
  font-family: 'Monoton', cursive;
  font-size: 8vw;
  display: block;
  margin: 0;
  color: orange;
  line-height: 8vw;
}

.homescreen__stats{
  text-transform: uppercase;
  font-size: 3vw;
  color: #fff;
  margin-bottom: .3em;
}

.homescreen__number{
  color: #ffcc00;
}

.homescreen__shuffle-button{
  font-size: 5vw;
  border-radius: 10em;
  border: 0;
  text-transform: uppercase;
  border: 2px solid white;
  color: orange;
  background-color: transparent;
  background: linear-gradient(to bottom, rgba(255,51,0,1)         0%,rgba(153,0,0,1) 100%);
  //width: 50%;
  outline: 0;
  transition: all .25s;
  transition-timing-function: ease-out;
  padding-left: 7vw;
  padding-right: 7vw;

  amp;:hover{
background: #990000;
letter-spacing: .1em;
//box-shadow: 0px 0px 5vw #ffcc00;
border-color: orange;
  }
}
  

Комментарии:

1. можете ли вы добавить css (homescreen.css) в вопрос?

Ответ №1:

 this.props.clickEvent(this.props.clickEvent);
  

Приведенный выше код должен совпадать с функцией GameOn в компоненте приложения.

если у функции GameOn нет параметра, вам нужно изменить его следующим образом;

   clickMe(){
//call parent function that manages state
      this.props.clickEvent();
  }
  

Компонент вашего приложения должен быть таким, как показано ниже;

 import React, { Component  } from 'react';

    export default class App extends React.Component{
        constructor(props){
            super(props);
            this.isGameOver = false;
            this.gamePlayed = 0;
        }

        gameOn(){
            this.isGameOver = !this.isGameOver;
            this.gamePlayed  =1;

        }
        render(){
            return(
                <Homescreen gameOver = {this.isGameOver} gamesWon = {this.gamesPlayed} clickEvent = {gameOn}/>

            )
        }

}
  

Комментарии:

1. Как будет выглядеть функция в приложении. Я не понимаю, как выполнить эту часть в App.js

Ответ №2:

Вам нужно определить функцию GameOn и, возможно, обновить состояние вашего приложения.

 var gamesPlayed = 0;
export default function App() {
  constructor(props){
    super(props);
    this.state = {
      gameStarted: false
    };
  }
  gameOn(){
    this.setState({gameStarted: true})
  }
  render(){
    return (
      <Homescreen clickEvent = { this.gameOn.bind(this) }/>
    )
  }
}
  

Теперь вы можете условно показывать и скрывать материал при рендеринге на основе state.gameStarted.

Примечание: Вам также необходимо привязать это к функции, чтобы это можно было использовать при обратном вызове, смотрите здесь (https://reactjs.org/docs/handling-events.html )

Комментарии:

1. возможно ли сделать это в приложении, используя перехваты, а не состояния

Ответ №3:

В вопросе есть некоторые части, которые неясны, но я полагаю, что вы хотите скрыть содержимое после нажатия кнопки «Пуск».

App.js

 class App extends Component {
  constructor() {
    super();
    this.state = {
      isGameOn: false,
      gamesPlayed: 0
    };
  }


  startGame = () => {
    this.setState({
      isGameOn: true,
      gamesPlayed: this.state.gamesPlayed   1
    })
    console.log(this.state.isGameOn);
  }

  render() {
    return (
      <Homescreen isGameOn = {this.state.isGameOn} gamesWon={this.state.gamesPlayed} clickEvent = {this.startGame}/>
    );
  }
}
  

Homescreen.js

 import React from 'react';
import './homescreen.css';
class Homescreen extends React.Component{
    constructor(){
      super();
      this.clickMe = this.clickMe.bind(this);
    }
    clickMe(){
      //call parent function that manages state
      this.props.clickEvent();

    }
    render(){
      return (
        <div className={!this.props.isGameOn ? "homescreen homescreen--visible" : "homescreen homescreen--hidden"}>
          <div className="homescreen__box">
            <h1 className="homescreen__title">Spaceamp;nbsp;  Matcher</h1>
            <div className="homescreen__stats">
              Games Played: <strong className="homescreen__number" >{this.props.gamesWon}</strong>
            </div>
            <button className="homescreen__shuffle-button " onClick={this.clickMe} >Start!</button>
          </div>
        </div>
      )
    }
}

export default Homescreen;
  

вот пример stackblitz

Комментарии:

1. Можно ли опустить состояния в приложении и использовать перехваты вместо этого?