简体   繁体   English

使用来自按键输入的对象更新状态[反应]

[英]Update state with object from key input [React]

I'm trying to update the state of my component based on key inputs, and pass it to another component. 我正在尝试根据按键输入更新组件的状态,并将其传递给另一个组件。

I can get call keyboardInput() and console.log the correctly when one of the arrow keys are pressed, however I cannot get the returned value to render in <p>The current input is: {this.keyboardInput}</p> 当按下其中一个箭头键时,我可以正确地调用keyboardInput()和console.log,但是我无法获得返回的值以呈现在<p>The current input is: {this.keyboardInput}</p>

Eg return {'Y': 1}; 例如return {'Y': 1}; when the up key is pressed, but nothing appears in the <p> element 当按下向上键,但<p>元素中什么都没有出现时

I believe I'm missing some understanding when it comes to the componentWillReceiveProps function, but I'm at a loss. 我相信我对componentWillReceiveProps函数缺少一些了解,但是我很茫然。

Could it be that keyboardInput is returning an object not a string value? 可能是keyboardInput返回的对象不是字符串值吗? But even when I change the return to just be a string, I still cannot get it to render. 但是即使将return更改为字符串,我仍然无法将其呈现。

What am I missing here? 我在这里想念什么?

Thanks, 谢谢,

class GameBoard extends Component {

    constructor(props) {
        super(props);
        this.state = {
            test: {},
        };
    }

    // Captures event from main window
        keyboardInput = (e) => {

            const code = e.keyCode ? e.keyCode : e.which;

            // Change X and Y values
            if (code === 38) { //up key
                return {'Y': 1};
            } else if (code === 40) { //down key
                return {'Y': -1};
            } else if (code === 37) { // left key
                return {'X': 1};
            } else if (code === 39) { // right key
                return {'X': -1};
            }
        };

    componentWillMount() {
        window.addEventListener('keydown', this.keyboardInput);
    }

    componentWillUnmount() {
        window.removeEventListener('keydown', this.keyboardInput);
    }

    componentWillReceiveProps(nextProps) {
        this.setState.test = this.keyboardInput(nextProps);
    }

    render() {

        return (
            <div>
                <p>The current input is: {this.keyboardInput}</p>
                <Ball/>
            </div>
        )
    }

}

class App extends Component {

  render() {

      const boardStyle = {
          'position': 'absolute',
          'backgroundColor': '#7f8c8d',
          'height': '100%',
          'width': '100%',

      };

    return (
      <div>
        <header>
          <h1 className="App-title">Welcome to Moving Objects</h1>
        </header>
          <div style={boardStyle}>
              <GameBoard/>
          </div>
      </div>
    );
  }
}

export default App;

Looks like there's some misunderstanding about React/JS constructs in general here. 看起来这里对React / JS构造有一些误解。

Hopefully the below will help you along, but you should definitely take a closer look at the React docs to get a better handle on what you're doing. 希望下面的内容对您有所帮助,但是您绝对应该仔细查看React文档,以更好地了解您的工作。

{this.keyboardInput} in your render function doesn't actually refer to anything here - this is referring to your GameBoard class, and then you're trying to access some member - be it a function, variable, whatever - called keyboardInput . render函数中的{this.keyboardInput}实际上并未在此处引用任何内容- this是在引用GameBoard类,然后您尝试访问某个成员-无论是函数,变量,还是任何东西-称为keyboardInput You don't have one. 你没有一个。

With React, what you would want to access is {this.state.keyboardInput} - what that is saying is this: In this (the GameBoard), I want to access its current state . 使用React,您要访问的是{this.state.keyboardInput} -就是这样:在this (游戏板)中,我想访问其当前state In that state , there is a field called keyboardInput . 在这种state ,存在一个名为keyboardInput的字段。 Render that. 渲染。

<p> The current input is: {this.state.keyboardInput} </p>

The second step is to actually set that state. 第二步是实际设置该状态。 It looks like you have calling your function keyboardInput down when the eventlistener picks up an event, but I think this is part of your issue: keyboardInput would be much better named something like onKeyboardInput or handleKeyboardInput . 看起来你已经调用你的函数keyboardInput下来时,事件侦听拿起一个事件,但我觉得这是你的问题的一部分: keyboardInput会好得多名字类似onKeyboardInputhandleKeyboardInput

Remember how we wanted to set the state? 还记得我们要如何设置状态吗? Inside that function, we're going to have to use React's setState function - it would look something like this: 在该函数内部,我们将不得不使用React的setState函数-它看起来像这样:

handleKeyboardInput = (e) => {
        const code = e.keyCode ? e.keyCode : e.which;

        if (code === 38) { //up key
            this.setState({ keyboardInput: {'Y', -1 }});
        }
}

This function is now saying, "Hey GameBoard , your state is going to now have a field keyboardInput , which will look like the object { 'Y', -1 } ." 此功能现在说,“嘿GameBoard ,你的状态将会现在有一个场keyboardInput ,这将类似于对象{ 'Y', -1 } 。”

Note that this in keyboardInput wants to refer to React's component, so we'll have to bind this in our listeners: 请注意, keyboardInput中的this要引用React的组件,因此我们必须在侦听器中绑定它:

componentWillMount() {
        window.addEventListener('keydown', this.handleKeyboardInput.bind(this));
}

All we're doing here is telling handleKeyboardInput to use the same this as componentWillMount . 所有我们要做的是告诉handleKeyboardInput使用相同的thiscomponentWillMount this in componentWillMount refers to our GameBoard component, so this in handleKeyboardInput will also refer to the GameBoard . componentWillMount this引用我们的GameBoard组件,因此handleKeyboardInput this也引用GameBoard We want this because handleKeyboardInput wants to call GameBoard 's .setState function. 我们之所以这样,是因为handleKeyboardInput要调用GameBoard.setState函数。

In general, that's how the flow of React goes: you'll want to set some state on a component using setState . 通常,这就是React流程的方式:您将需要使用setState在组件上设置一些state After that's done, you can read it out in your render function (or any other function for that matter) by saying this.state.foobar . 完成之后,您可以通过说出this.state.foobar ,在render函数(或与此相关的任何其他函数)中读出它。

In this example, we start at our listener. 在此示例中,我们从侦听器开始。 We see a keypress event, and say, go handle whatever we need to do at handleKeyboardInput ! 我们看到一个按键事件,并且说,要处理我们需要在handleKeyboardInput上做的所有事情! handleKeyboardInput says GameBoard ! handleKeyboardInputGameBoard Your state is keyboardInput: foo . 您的状态为keyboardInput: foo All the while, render is looking GameBoard 's state (the keyboardInput !) to display. 一直GameBoard ,渲染器一直在显示GameBoard的状态( keyboardInput !)。

Like I said, this is a pretty informal rundown of states in React - definitely take a look at React's documentation, and maybe work through an example project they have to really let it sink in. 就像我说的那样,这是React中状态的一个非常非正式的总结-一定要看一下React的文档,也许通过一个示例项目来工作,他们必须让它沉入其中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM