假设:
Welcome.js
import React from 'react';
import WorkPlacePage from '../../components/welcome/WorkPlacePage';
import SkillPage from '../../components/welcome/SkillPage';
class Welcome extends React.Component {
constructor(props) {
super(props);
switch (props.match.params.welcomeId) {
case "workplace":
this.state = { step: 1 };
break;
case "skills":
this.state = { step: 2 };
break;
default:
this.state = { step: 1 };
break;
}
console.log(this.state)
}
nextStep(props) {
console.log('nextStep')
console.log(this)
this.setState({
step : this.state.step + 1
})
}
showStep(props) {
const {history} = this.props
switch (this.state.step) {
case 1:
return <WorkPlacePage history={history}
nextStep={this.nextStep} />
case 2:
return <SkillPage history={history}
nextStep={this.nextStep} />
default:
return (
<div>
<h1>Case: Default</h1>
</div>
);
}
}
render() {
var style = {
width : (this.state.step / 4 * 100) + '%'
}
return (
<main>
<span className="progress-step">Step {this.state.step}</span>
<progress className="progress" style={style}></progress>
{this.showStep()}
</main>
)
}
}
export default Welcome;
WorkPlacePage.js
导入来自&#39;的反应&#39 ;; 从&#39; history / createBrowserHistory&#39;;
导入createBrowserHistoryclass WorkPlacePage扩展了React.Component {
saveAndContinue =(e)=&gt; { //e.preventDefault() this.props.nextStep() }
render(){
const history = createBrowserHistory();
return (
<div>
<h1>Workplace</h1>
<span>
survey things
// <button onClick={() => history.push('/welcome/skills')}>next page</button>
</span>
<button onClick={() => this.saveAndContinue() }>XXX page</button>
</div>
);
} }
导出默认的WorkPlacePage;
点击按钮后,我收到this.props.nextStep()
Uncaught TypeError: Cannot read property 'props' of null
我做错了什么?感谢
答案 0 :(得分:4)
您需要将组件的$options[0][0]->my_callback('HELLO');
绑定到您的函数。
您可以使用ES6胖箭头语法:
their_caller
或者你可以在构造函数中绑定它:
their_callback
编辑:回答你剩下的错误:
只要您在函数中使用this
或saveAndContinue = (e) => {
e.preventDefault()
this.props.nextStep()
}
,就必须确保从组件中绑定constructor(props) {
super(props);
this.saveAndContinue = this.saveAndContinue.bind(this);
}
。
因此,在this.props
中,更改this.state
和this
函数以使用ES6胖箭头语法。
关于Welcome.js
的错误,这是因为您没有将事件传递给您的函数。因此,您需要进行以下更改:
nextStep
更改为:
showStep
答案 1 :(得分:1)
您需要bind
上下文。否则React无法识别它。在这里,我以现在的方式更改了代码。
import React, { Component } from 'react';
import WorkPlacePage from './WorkPlacePage'
class Welcome extends Component {
nextStep() {
console.log('Next Step callback is invoked !');
}
render(){
return <WorkPlacePage nextStep={this.nextStep.bind(this)} />
}
}
export default Welcome
import React, { Component } from 'react';
class WorkPlacePage extends Component {
saveAndContinue() {
console.log('Invoking function passed from the parent');
this.props.nextStep()
}
render() {
return (
<div>
<button onClick={ this.saveAndContinue.bind(this) }>Save and Continue</button>
</div>
);
}
}
export default WorkPlacePage
希望这会有所帮助。快乐的编码!