通过Context Api传递的方法,在按钮onClick方法(相同形式)内运行良好, 但在表单onSubmit方法中不起作用。
Gdpr.js
render() {
return (
<MyContext.Consumer>
{(context) => (
<div>
<form onSubmit={context.onSubmitGdpr}>
<FormattedMessage id='app.terms'/>
<div>
<label className="container"><strong><FormattedMessage id={"app.terms.agree"}/></strong>
<input type="checkbox" checked={this.state.agree} onChange={this.onChangeHandler}/>
</label>
<Link to={context.state.nextStageAfterGDPR ? context.state.nextStageAfterGDPR : "#"}>
<button disabled={!this.state.agree}><FormattedMessage id='app.buttons.submit'/>
</button>
</Link>
</div>
</form>
</div>
)
}
</MyContext.Consumer>
)
}
export default Gdpr
MyProvider.js
通过Context API提供程序传递的方法是...
onSubmitGdpr = (e) => {
e.preventDefault()
fetch("/api/v1/gdpr")
.then(res=> res.json())
.then(data => { this.setState({nextStageAfterGDPR: "./camera-intro"})
})
.catch(error=>console.log(error))
}
MyProvider.js继续...
render() {
return (
<MyContext.Provider value={{
state: this.state,
onSubmitStart: this.onSubmitStart,
onSubmitGdpr: this.onSubmitGdpr
}}>
{this.props.children}
</MyContext.Provider>
)
}