javascript - 如何从另一个类访问ReactJS中渲染内的变量(编辑: another js page) (ES6 and Node is being used)

标签 javascript reactjs ecmascript-6

我想在游戏的 AI 移动时禁用 onClick(startThinking 函数),这样玩家就不会随机点击游戏的任何部分并弄乱它。

这是我想要访问变量 onclick 和cursor 的类的代码(相关位由 ** ** 包围):

class Grid extends React.Component{
        constructor(props){
          super(props);
          var pos = props.pos;
          this.xPos = 2+(pos%9)*66+"px";
          this.yPos = 2+(Math.floor(pos/9))*66+"px";
          this.borderTop = "none";
          this.borderLeft = "none";
          this.borderRight = "none";
          this.borderBottom = "none";
          if(pos%3==0){
            this.borderLeft = "solid";
          }
          if(pos%9==8){
            this.borderRight = "solid";
          }
          if(pos>71){
            this.borderBottom = "solid";
          }
          if((pos%27)<9){
            this.borderTop = "solid";
          }
      }

        render(){
          var pos = this.props.pos;
          var icon = this.props.icon;
          var backgroundColor = (icon==="none")?((!this.props.legal)?((pos%2)?"white":"#f2f2f2"):((pos%2)?"rgb(177, 251, 169)":"rgb(157, 228, 150)")):((icon==="x")?"rgb(243, 125, 125)":"#6f83f3");
          var choice = "";
          var **onclick** = (this.props.legal)?this.props.onclick:(()=>{});
          var **cursor** = (this.props.legal)?"pointer":"default";
          if(icon !== "none"){
              choice = (<div className='icon'>{icon}</div>);
          }
          return(<div onClick={onclick} style={{cursor:cursor,backgroundColor:backgroundColor,top:this.yPos,left:this.xPos,borderLeft:this.borderLeft,borderRight:this.borderRight,borderTop:this.borderTop,borderBottom:this.borderBottom}} className='grid' >{choice}</div>);
        }
      }

这是我想要访问变量 onclick 和光标的类,并在 gameAI 开始思考之前将它们更改为默认值(即不活动),然后我想在 gameAI 完成后将它们恢复为原始值思考并采取了行动。相关位被 ** ** 包围

class Board extends React.Component {
        constructor(props){
          super(props);
          this.state = {
            model: curGame
          }
          setSimBoard(this);
        }

        render() {
          var model = this.state.model;
          var i = -1;

          var comps = model.grid.map((sq)=>{
            i++;
            var n = "block_"+i;
            var leg = model.legals.indexOf(i)>-1;
            return <Grid id={n} key={n} pos={i} icon={sq.icon} legal={leg} onclick={
              ((i)=>{
                  **  return ()=>{
     // the comments are what i tried, didn't work    Grid.onclick = (()=>{});
                    //  Grid.cursor = "default";
                      startThinking(i);
                      model.makeMove(i);
                   //   Grid.onclick = (this.props.legal)?this.props.onclick:(()=>{});
                    //  Grid.cursor = (this.props.legal)?"pointer":"default";
                      this.setState({model:model});

                    }
                  })(i) **
            }/>;
          });

          return (
            <div>
              <div>{comps}</div>
              <BoardStatus model={model}/>
              <WinCover model={model}/>
            </div>
          );
        }
      }

最后,这是startThinking函数,它位于另一个js文件中。评论是我尝试过的。 ai 属于另一个文件,即 gameAI,它正在执行移动计算。

function startThinking(i){
  //document.getElementById('id').style.pointerEvents = 'none'; 
  console.log("thinking..");
  ai.postMessage({game:Object.assign({"ai":true}, curGame) ,move:i});
//  document.getElementById('id').style.pointerEvents = 'auto';  
}

我真的很感谢对此的帮助!非常感谢!

编辑:所以,Pranesh Ravi 告诉我如何从另一个类中的一个类访问变量。但是,由于这没有解决我的问题,我想知道如何从另一个文件 ai.js 访问 onclick 和光标变量,其相关部分如下所示, super 相关部分由 * 包围* **。评论是我在 gameAI 工作时尝试禁用点击的内容,这给了我一个引用错误,说 Board is not returned 这是有道理的。

    var thinkTime = 2000;
    var think = false;
    var maxDepth = 6;
    onmessage = function(msg){
   ** //  Board.onclick = (()=>{});
    //  Board.cursor = "default"  **
      var game = msg.data.game;
      var playerMove = msg.data.move;
      think = true;
      var search = new SearchTree(game,playerMove,0);
      var bestMove = search.traverse(maxDepth,true);
      console.log(bestMove);
      postMessage(bestMove.move);
  **   // Board.onclick = (this.props.legal)?this.props.onclick:(()=>{});
     // Board.cursor = (this.props.legal)?"pointer":"default";  **
}

最佳答案

这是像 Redux 这样的库可以解决的问题。

您有一个包含游戏状态信息的中央存储库。我可以给你两种方法来解决这个问题。

选项 1. 获取 Grid 组件的引用并调用返回所需信息的函数。

选项 2。由于获取组件的引用是不好的做法,因此更纯粹的方法是在渲染子组件时将函数传递给子组件。它用于注册一个函数来获取您需要的信息。这是我推荐的方法。

class Board extends Component {

  constructor(props) {
    super(props);
    this.registerStateFetcher = this.registerStateFetcher.bind(this);
  }

  registerStateFetcher(fetcher) {
    this.stateFetcher = fetcher;
  }

  render() {
    return <Grid registerStateFetcher={ this.registerStateFetcher } />
  }
}

class Grid extends Component {

  constructor(props) {
    super(props);
    props.registerStateFetcher(this.getGameState.bind(this));
  }

  getGameState() {
    // recollect info needed and return
    return {};
  }

}

关于javascript - 如何从另一个类访问ReactJS中渲染内的变量(编辑: another js page) (ES6 and Node is being used),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40325791/

相关文章:

ruby-on-rails - rails api 和 react api 的分页

node.js - Webpack 在 linux 上找不到 lodash 子模块,但在 macOS 上可以正常工作

javascript - 如何调试 JS 代码中的 "not found"消息?

javascript - sap 服务器上的代理 servlet web-inf/web.xml 以调用外部 REST

javascript - href 链接在标题标记中不起作用

reactjs - 将 props 从父组件传递到子组件

javascript - 在 JavaScript 中从序列化 JSON 对象中提取变量

javascript - ReactJs选择,没有值显示

typescript - 使用解构/扩展在 TypeScript 中复制具有重命名属性的对象

javascript - JS中这个表示法是什么,有人可以解释一下吗