程式码片段
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,因此不会引用组件实例,因此应手动绑定它。有几种方法:
React.createClass
this
1.手动绑定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.this在呼叫站点绑定
在render()方法中:
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>; } } }