【问题标题】:React pass method as prop got undefined of another method反应传递方法作为道具未定义另一种方法
【发布时间】:2017-08-30 13:50:19
【问题描述】:
import ImageGallery from 'react-image-gallery'

    methodOne(){
       return (<div><ImageGallery /></div>)
    }

    methodTwo(){
       return (<h1>{this.methodOne()}</h1>)
    }

    render() {
       return(
         <AnotherCommonComponent methodTwo={this.methodTwo} />
       )
    }

当我尝试将 methodTwo 作为 prop 传递给另一个组件时,我得到了未定义的 methodOne。奇怪的是,当我直接渲染时,我可以让 methodOne 工作

render() {
       return(
         <methodTow />
       )
    }

是因为this 的问题吗?我什至尝试过

 methodOne = () => {
       return (<h1>h1 here</h1>)
    }

没有任何效果。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    语法错误,改成下面提到的代码。

    render() {
           return(
             {this.props.methodTwo()}
           )
        }

    【讨论】:

    • 现在可以查看了。
    • 你想证明什么? methodOne 与 methodTwo 处于同一级别。
    【解决方案2】:

    您必须将 this 运算符绑定到函数。 你可以在构造函数中这样做

    ....
    
    constructor(props) {
      super(props);
      
      this.methodOne = this.methodOne.bind(this);
      this.methodTwo = this.methodTwo.bind(this);
    }
    
    methodOne(){
       return (<h1>h1 here</h1>)
    }
    
    methodTwo(){
       return (<h1>{this.methodOne()}</h1>)
    }
    
    render() {
       return(
         <AnotherCommonComponent methodTwo={this.methodTwo} />
       )
    }

    【讨论】:

    • 你测试过这段代码吗?我试过了还是不行,methodOne内容没有出现,没有错误。
    • 怎么调用methodTwo?
    • 想通了,需要用div换行
    • 在 JavaScript 中,函数中的 this 始终等于 global 对象。也就是说,当不与.call().bind().apply() 一起使用时。您还可以使用箭头函数来自动更改 this 的上下文,它使用 lexical scoping 这意味着 this 指的是封闭环境 - 在这种情况下是您的 React 组件。
    【解决方案3】:
    methodOne(){
      return (<h1>h1 here</h1>)
     }
    
      methodTwo(){
        return (<h1>{this.methodOne()}</h1>)
     }
    
    render() {
      return(
        <AnotherCommonComponent methodTwo={this.methodTwo.bind(this)} />
      )
     }
    

    您需要将 this 绑定到 this.methodTwo 以访问 AnotherCommonComponent 中的方法一。 希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 2020-11-27
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多