【发布时间】:2018-04-16 00:04:59
【问题描述】:
我正在尝试将函数向下传递给反应路由器中的子组件。我已经弄清楚如何使用 render 来发送我的道具,并正在使用 withRouter 使它们可用于我当前的状态。
我无法让函数传递给接收它的组件定义的另一个函数。
下面的示例代码 - 有点切碎
// generic class with a router attempting to pass a function to a child
class App extends Component{
...
modalLogin = () => {
console.log('modal login called')
this.setState({modalLoginTrigger:true})
}
render(){
render(
<router>
<switch>
<Router ....more paths>
<Route path='/product/:_id' render={(props) =>(<ProductPage onModalLogin={this.modalLogin} />)}/>
</siwtch>
</router>)
ProductPage - 正确接收所有父 props,但未将 addToBinder() 函数连接到 this.props.onModalLogin
class ProductPage extends Component {
addToBinder(){
this.props.onModalLogin()
}
render() {
<div>
<a className="cb_binder-link__add-remove col-xs-6" onClick={this.addToBinder} href="#">
</div>
}
export default withRouter(ProductPage) ;
当我的锚点中的 onclick 函数被调用时,我得到一个
TypeError:无法读取未定义的属性“道具” 这是来自 addToBinder()
当我从渲染器本身调用 onModalLogin 函数时,它可以工作。
class ProductPage extends Component {
addToBinder(){
this.props.onModalLogin()
}
render() {
<div>
<a className="cb_binder-link__add-remove col-xs-6" onClick={this.props.onModalLogin} href="#">
</div>
}
export default withRouter(ProductPage) ;
我希望能够在调用 onModalLogin 之前在 addToBinder 中执行业务逻辑 - 例如检查用户是否登录,如果没有则提示登录。如何连接?
【问题讨论】: