Reactjs-值未定义
Reactjs - value undefined
首先,我怀疑const vector对象可能放错了地方,但我不知道该放在哪里。我试图用箭头键控制SVG对象的位置。它似乎无法访问x.
class Circle extends React.Component {
render() {
const { h, w, x, y, r, stroke, fill } = this.props;
return (
<svg height={h} width={w}>
<circle cx={x} cy={y} r={r}
stroke={stroke} strokeWidth="3" fill={fill}
/>
</svg>
)
}
}
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
h: 100,
w: 500,
x: 50,
y: 50,
r: 40,
stroke: "black",
fill: "red"
}
}
_currentPosition() {
// Display the current position
console.log(this.state.x, this.state.y);
}
_handleKey(e){
// Define key codes and movement vectors
const vector = {
37: [-10, 0],
38: [0, -10],
39: [10, 0],
40: [0, 10]
};
// Display the current position
this.currentPosition;
// Detect key presses and change the position accordingly
if (e.keyCode in vector) {
this.setState({
x: this.state.x + vector[e.keyCode][0],
y: this.state.y + vector[e.keyCode][1]
})
}
}
componentDidMount() {
document.addEventListener("keydown", this._handleKey, false);
}
render() {
return (
<div>
<Circle { ...this.state } onKeyPress={this.handleKeyPress}/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
我得到了错误:
VM211 pen.js:76Uncaught TypeError: Cannot read property 'x' of undefined
_handleKey @ VM211 pen.js:76
代码是:http://codepen.io/wasteland/pen/GZvWeo?editors=0110
感谢
您的问题是this.state
在_handleKey
内部未定义。解决方案是将函数绑定到构造函数中的this
,如下所示:
constructor(props) {
super(props)
this._handleKey = this._handleKey.bind(this)
...
...
这通常是允许类方法访问类实例"this
"的方式。
关于"无自动绑定"的React文档:https://facebook.github.io/react/docs/reusable-components.html#no-自动绑定
相关文章:
- ReactJS中未定义组件
- 未捕获的类型错误:无法读取属性'道具'reactJS中未定义的
- Reactjs-值未定义
- 捆绑的JS reactjs上需要未定义的错误
- ReactJS打字稿事件此未定义
- ReactJS无法读取未定义的属性“setState”
- ReactJS - {this.props.children} 是未定义的
- 为什么我被未定义不是一个函数,ReactJs
- Reactjs:未定义文档
- 静态方法在 ES6 类中未定义,在 reactjs 中有一个装饰器
- ReactJS 无法读取未定义的属性“绑定”
- 未捕获的类型错误:无法读取属性'选中'的未定义-ReactJS
- ReactJS中初始状态的未定义值
- webpack reactjs应用程序加载失败:Uncaught ReferenceError:未定义snapapp
- Reactjs:作为道具访问时未定义的键
- Reactjs路由器匹配回调参数总是未定义的
- ReactJS映射函数找不到未定义的属性
- ReactJS: '类型未定义'加载组件时
- REACTJS getDOMNode在未定义的动态refs上出错
- Reactjs,这.上下文在构造函数方法中未定义