好心的注意:这里是新手。 这个问题看似微不足道,但对我来说似乎很难。
我当时正在修改Reactjs教程,在那里我陷入了一个非常琐碎的问题。
function Square(props) {
return (
<button className="square"> {props.value} </button>
);
}
class Board extends React.Component {
renderSquare(i) {
return <Square />;
}
render() {
return (
<div className="status">{this.props.printStatus()}</div>
);
}
}
export default class Game extends React.Component {
// COnstructor
constructor(props) {
super(props);
this.state = {
myProp: 'Hi'
}
}
// Gets gameplay status
getStatus() {
return this.state.myProp; // error coming here
}
render() {
return (
<div className="game">
<div className="game-board">
<Board printStatus={this.getStatus}/>
</div>
</div>
);
}
}
我在TypeError:无法读取未定义
的属性“my prop”时遇到错误:
这意味着组件game
的state
内部的属性myprop
不可访问或未被读取。 问题可能是什么?
这是因为将this.getStatus
直接传递给子组件会丢失它的调用方(this)。 相反,您可以传递它的“包装版本”。
此闭包将保留getStatus
的调用方,从而返回正确的值。
null
function Square(props) {
return (
<button className="square"> {props.value} </button>
);
}
class Board extends React.Component {
renderSquare(i) {
return <Square />;
}
render() {
return (
<div className="status">{this.props.printStatus()}</div>
);
}
}
class Game extends React.Component {
// COnstructor
constructor(props) {
super(props);
this.state = {
myProp: 'Hi'
}
}
// Gets gameplay status
getStatus() {
return this.state.myProp;
}
render() {
return (
<div className="game">
<div className="game-board">
<Board printStatus={() => this.getStatus()}/>
</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<Game />,
rootElement
);
<div id="root">
</div>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
您需要将this
绑定到构造函数
中的getStatus
函数。
constructor(props) {
super(props);
this.state = {
myProp: 'Hi'
};
this.getStatus = this.getStatus.bind(this);
}
https://gist.github.com/fongandrew/f28245920a41788e084d77877e65f22f
或者您可以将getStatus定义为箭头函数:
getStatus = () => this.state.myProp
查看以下内容:https://medium.com/byte-sized-react/what-is-this-in-react-25c62c31480