javascript - React JS 父子组件事件共享

标签 javascript reactjs ecmascript-6

下面是我的 react 组件,在这里我尝试创建父组件,它负责获取键盘事件“keyPressed”,并且无论按下哪个键,它都应该从 View 中删除匹配的子组件。

感谢您的帮助和建议。

父组件 该组件负责创建字符(a-z、A-Z)数组并创建一个板来将每个字符显示为名为 ball 的子组件。

import React, { Component } from "react";
import Ball from "./Ball";

export default class Board extends Component {
  constructor(props) {
    super(props);
    this.state = {
      letters: []
    };
    this.shuffle = this.shuffle.bind(this);
    this.handleEvent = this.handleEvent.bind(this);
  }

  componentDidMount() {
    const self = this;
    let letters = [];

    // small a - z
    for (let i = 97; i < 123; i++) {
      letters.push({ letter: String.fromCharCode(i), code: i });
    }

    // capital A - Z
    for (let i = 65; i < 91; i++) {
      letters.push({ letter: String.fromCharCode(i), code: i });
    }

    this.setState(state => ({
      letters: self.shuffle(letters)
    }));
  }

  shuffle(arr) {
    var ctr = arr.length,
      temp,
      index;

    // While there are elements in the array
    while (ctr > 0) {
      // Pick a random index
      index = Math.floor(Math.random() * ctr);
      // Decrease ctr by 1
      ctr--;
      // And swap the last element with it
      temp = arr[ctr];
      arr[ctr] = arr[index];
      arr[index] = temp;
    }
    return arr;
  }

  handleEvent(e) {
    const k = e.charCode;
    // HELP NEEDED HERE
    // Need to find matching children component of Ball to trigger its own setVisibility method.
  }

  render() {
    let ball = this.state.letters.map(item => {
      return <Ball key={item.code} properties={item} bouncing={true} />;
    });

    return (
      <div
        className="overlay-full game"
        onKeyPress={event => this.handleEvent(event)}
        tabIndex="0"
      >
        <div className="bubble-wrapper">{ball}</div>
      </div>
    );
  }
}

子组件 每个 Ball 组件都应该有自己的可见状态,如果它的状态是可见的,那么它只会在屏幕上渲染,否则它不应该执行任何操作。

import React, { Component } from "react";

export default class Ball extends Component {
  constructor(props) {
    super(props);
    this.getRandomSize = this.getRandomSize.bind(this);
    this.getRandomColor = this.getRandomColor.bind(this);
    this.setVisibility = this.setVisibility.bind(this);
    this.state = {
      isVisible: true,
      code: this.props.properties.code,
      letter: this.props.properties.letter
    };

    this.ballRef = null;
    this.setBallRef = element => {
      this.ballRef = element;
    };
  }
  getRandomSize() {
    const sizes = ["size-1", "size-2", "size-3", "size-4"];
    return sizes[Math.floor(Math.random() * 4)];
  }
  getRandomColor() {
    const colors = [
      "#55efc4",
      "#81ecec",
      "#74b9ff",
      "#a29bfe",
      "#00b894",
      "#00cec9",
      "#0984e3",
      "#6c5ce7",
      "#ffeaa7",
      "#fab1a0",
      "#ff7675",
      "#fd79a8",
      "#fdcb6e",
      "#e17055",
      "#d63031"
    ];
    return colors[Math.floor(Math.random() * 15)];
  }
  setVisibility(key) {
    if (this.state.code === key) {
      this.setState(state => ({
        isVisible: false
      }));
    }
  }
  render() {
    const { code, letter } = this.state;
    const isBouncing = this.props.bouncing ? "bouncing" : "";
    const isVisible = this.state.isVisible;
    const size = this.getRandomSize();
    const inlineStyle = {
      backgroundColor: this.getRandomColor()
    };

    if (isVisible) {
      return (
        <div
          className={`ball-${code} ${size} ${isBouncing}`}
          style={inlineStyle}
          ref={this.setBallRef}
        >
          {letter}
        </div>
      );
    } else {
      return null;
    }
  }
}

最佳答案

我认为您需要使用 Redux 来解决此类问题,这样您就不会在管理整个应用程序的状态时遇到麻烦。

但是如果您需要遵循当前场景,那么您需要使用 refs。 React 提供 CreateRef API。使用它,您可以获得对 Ball 组件的引用并触发它的 setVisibility 方法。但在此之前,您需要通过提供回调函数将相应 Ball 组件的状态提升到父组件。

关于javascript - React JS 父子组件事件共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58395376/

相关文章:

javascript - 如何将 typescript 项目与 html 集成

javascript - 如何将日本国旗字符🇯🇵放入字符串中?

java - 将 setText 用于 EditText 框,onClick 认为它为空

reactjs - 需要一个参数取决于另一个参数的存在

reactjs - 在react与redux中,如何进行post请求

javascript - 如果在React中的onClick中放置两个函数,则只有其中一个可以工作

javascript - 在原型(prototype)中保留 'this' 上下文

javascript - 如何使用箭头键在浏览器中重新加载新的 URl

javascript - 在 ReactJS 中为复选框选择限制功能添加最小值和最大值

javascript - 在异步等待中返回未决的 promise