【问题标题】:React Passing Component Function - cannot use in functionReact 传递组件函数 - 不能在函数中使用
【发布时间】: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 中执行业务逻辑 - 例如检查用户是否登录,如果没有则提示登录。如何连接?

【问题讨论】:

    标签: reactjs react-router-v4


    【解决方案1】:

    看起来您需要将其绑定到您的 addToBinder 函数,因此请尝试: onClick={() => this.addToBinder()} 或 onClick={this.addToBinder.bind(this)}

    或者实际上,看看你是如何定义 modalLogin 的,只需对 addToBinder 做同样的事情,它会自动将 this 绑定到函数,这样你就不必执行上述任何一种方法。这就是当您将 this.modalLogin 传递给 onClick 时它起作用的原因。

    【讨论】:

      【解决方案2】:

      事实证明,我需要将我的 onClick 绑定到 This

      class ProductPage extends Component {
         addToBinder(){
            this.props.onModalLogin()
         }   
      
         render() {
             <div>
                 <a  onClick={this.props.onModalLogin.bind(this)} href="#">
             </div>
         }
      }
      

      跟进 Dal 提供的另一个答案,重新定义 addToBinder 函数,将范围传递给父级。

      addToBinder = () => {
          this.props.onModalLogin()
      }
      

      这也很干净。

      【讨论】:

        猜你喜欢
        • 2020-07-26
        • 2020-09-07
        • 2021-06-16
        • 2018-12-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-25
        • 1970-01-01
        • 2021-04-24
        相关资源
        最近更新 更多