我正在尝试根据键输入更新组件的状态,并将其传递给另一个组件。
当按下其中一个箭头键时,我可以正确调用keyboardInput()
和console.log,但是我无法在<p>The current input is: {this.keyboardInput}</p>
中获取返回值
例如。按下向上键时return {'Y': 1};
,但<p>
元素中没有任何内容
我相信我在componentWillReceiveProps
功能方面缺少一些理解,但我很茫然。
是不是keyboardInput
返回一个对象而不是字符串值?但即使我将返回更改为只是一个字符串,我仍然无法让它呈现。
我在这里错过了什么?
谢谢,
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;
看起来这里有一些关于React / JS结构的误解。
希望以下内容对您有所帮助,但您一定要仔细查看React文档,以便更好地处理您正在做的事情。
你的{this.keyboardInput}
函数中的render
实际上并没有引用任何东西 - this
指的是你的GameBoard
类,然后你试图访问一些成员 - 无论是函数,变量,无论如何 - 称为keyboardInput
。你没有。
使用React,你想要访问的是{this.state.keyboardInput}
- 这就是说:在this
(GameBoard),我想访问它当前的state
。在那个state
,有一个叫做keyboardInput
的领域。渲染一下。
<p> The current input is: {this.state.keyboardInput} </p>
第二步是实际设置该状态。看起来你在eventlistener选择事件时调用了你的函数keyboardInput
,但我认为这是你问题的一部分:keyboardInput
会更好地命名为onKeyboardInput
或handleKeyboardInput
。
还记得我们想要设置状态吗?在该函数内部,我们将不得不使用React的setState函数 - 它看起来像这样:
handleKeyboardInput = (e) => {
const code = e.keyCode ? e.keyCode : e.which;
if (code === 38) { //up key
this.setState({ keyboardInput: {'Y', -1 }});
}
}
这个功能现在说,“嘿GameBoard
,你的州现在将有一个字段keyboardInput
,看起来像{ 'Y', -1 }
对象。”
请注意,this
中的keyboardInput
想要引用React的组件,因此我们必须在我们的侦听器中绑定它:
componentWillMount() {
window.addEventListener('keydown', this.handleKeyboardInput.bind(this));
}
我们在这里所做的就是告诉handleKeyboardInput
使用与this
相同的componentWillMount
。 this
中的componentWillMount
指的是我们的GameBoard
成分,因此this
中的handleKeyboardInput
也将指代GameBoard
。我们想要这个因为handleKeyboardInput
想要调用GameBoard
的.setState
函数。
一般来说,这就是React的流程:你需要使用state
在组件上设置一些setState
。完成后,你可以通过说render
在你的this.state.foobar
函数(或任何其他函数)中读出来。
在这个例子中,我们从听众开始。我们看到一个按键事件,并且说,在handleKeyboardInput
处理我们需要做的任何事情! handleKeyboardInput
说GameBoard
!你的州是keyboardInput: foo
。一直以来,渲染都在寻找GameBoard
的状态(keyboardInput
!)来展示。
就像我说的,这是React中状态的非常非正式的概述 - 绝对可以看看React的文档,也许可以通过一个示例项目来实现它们真正让它沉入其中。