小编Har*_*rry的帖子

有没有办法将组件引用存储在状态中?或者一个更“react-y”的替代方案?

我正在编写一个“配对”游戏,需要将两个单击的卡组件的引用存储在父状态中,这样当单击第三张卡时我可以将它们“翻转”回来。有没有办法将引用存储在可访问的状态中?

所以我有一个 4x4 网格 16 卡,我首先尝试为每张卡创建一个引用(a1、a2、a3、a4、b1 等),并将这些引用传递给组件。这适用于在这些组件上运行方法,但仅当我显式键入引用时,例如 Flip(this.a1.current)。

但是,我无法将该引用存储在其他任何地方,因此我无法在

class Game extends Component {
  constructor(props) {
    super(props);
    this.state= {
     lefthand: this.a1.current;
Run Code Online (Sandbox Code Playgroud)

有没有办法将引用存储在状态中以供以后使用?

class Game extends Component {

  constructor(props) {
    super(props);
    this.a1= React.createRef();
    this.a2= React.createRef();
    this.a3= React.createRef();
    this.a4= React.createRef();
    //etc
    this.state= {
      leftHand: '',
      rightHand: '',
    };
  }

  setLeftHand = (card) => {
    this.setState ({
      leftHand: card
    })
  }

  setRightHand = (card) => {
    this.setState ({
      rightHand: card
    })
 }


  render() {
    return (
      <div className="Game">
        <table>
          <tbody>
            <tr>
              <Card setlh={this.setLeftHand} …
Run Code Online (Sandbox Code Playgroud)

jsx reactjs

6
推荐指数
1
解决办法
9616
查看次数

标签 统计

jsx ×1

reactjs ×1