- 我有一个 react 代码
- 此代码在 UI 中呈现各种面板。
- 当我点击一个标签时,这个函数被称为sportsCornerPanel()
- 但我得到了 Uncaught TypeError 如何解决它
- 在下面提供代码段。
- 您可以在 fiddle 中看到完整的代码
代码片段
sportsCornerPanel() {
debugger;
console.log("sportsCornerPanel"
console.log("this.props.sportsPanelState.size-->" + this.props);
if (this.props.sportsPanelState.size === 'hidden') {
if (!this.props.sportsPanelState.visible) {
this.props.dispatch(sportsOpenPanel());
} else {
this.props.dispatch(sportsClosePanel());
}
}
}
render() {
let sportsContent, leftNavLink;
if (this.props.sports-layout !== 'small') {
console.log("SportsBox---page loads at bigger size");
console.log("SportsBox---page loads at ipad size");
sportsContent = <SportsBox className="sports-header"/>;
} else {
if (this.props.sportsPanelState.visible) {
console.log("sportsPanelState--when it becomes small--around ipad width");
sportsContent = <SportsBox className="sports-nav"/>;
leftNavLink = <a onClick={this.sportsCornerPanel} href="javascript:;" className="header-navLink active"></a>;
} else {
if (this.props.sports.active) {
console.log("SportsBox");
sportsContent = <SportsBox className="sports-nav"/>;
} else {
console.log("leftNavLink--when it becomes small--around ipad width");
leftNavLink = <a onClick={this.sportsCornerPanel} href="javascript:;" className="header-navLink"></a>;
}
}
}
output
Uncaught TypeError: Cannot read property 'props' of null
最佳答案
由于你没有在类方法中使用 React.createClass
this
不引用组件实例,所以你应该手动绑定(bind)它。有几种方法:
1.在类构造函数中手动绑定(bind)this
constructor(props) {
super(props);
this.sportsCornerPanel= this.sportsCornerPanel.bind(this);
}
<强>2。使用带有箭头函数的 ES7 属性初始化器
sportsCornerPanel = () => {
debugger;
console.log("sportsCornerPanel"
console.log("this.props.sportsPanelState.size-->" + this.props);
if (this.props.sportsPanelState.size === 'hidden') {
if (!this.props.sportsPanelState.visible) {
this.props.dispatch(sportsOpenPanel());
} else {
this.props.dispatch(sportsClosePanel());
}
}
}
3.在调用点绑定(bind) this
在render()
方法中:
let sportsContent, leftNavLink;
if (this.props.sports-layout !== 'small') {
console.log("SportsBox---page loads at bigger size");
console.log("SportsBox---page loads at ipad size");
sportsContent = <SportsBox className="sports-header"/>;
} else {
if (this.props.sportsPanelState.visible) {
console.log("sportsPanelState--when it becomes small--around ipad width");
sportsContent = <SportsBox className="sports-nav"/>;
leftNavLink = <a onClick={this.sportsCornerPanel.bind(this)} href="javascript:;" className="header-navLink active"></a>;
} else {
if (this.props.sports.active) {
console.log("SportsBox");
sportsContent = <SportsBox className="sports-nav"/>;
} else {
console.log("leftNavLink--when it becomes small--around ipad width");
leftNavLink = <a onClick={this.sportsCornerPanel.bind(this)} href="javascript:;" className="header-navLink"></a>;
}
}
}
关于javascript - 未捕获的类型错误 : Cannot read property 'props' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35303490/