[React] 透过 Props 将 变数 或 (自己)物件 往父层传递

透过这样的作法
可以让其他元件与元件之间 互相 呼叫 或 操作内部 函式

A 父层

abc(v){ console.log(v)// value1}    <ComponentA        funA={(ref) => this.abc(ref)}    />

B 子层 ( ComponentA 内)

  function(){  this.props.funA("value1")  }

将 ComponentA 传递至父层 再将 ComponentA 传递给 ComponentB

step1
ComponentA 物件

    componentDidMount() {        this.props.onRef(this)        //把自己this透过 props 往上传递    }

step2 在父层接到 ComponentA回传自己,
再将自己塞到 父层 state

funA(comp){  comp = this.setState({objA:comp})}<ComponentA      onRef={(comp)=>{this.funA(comp)}}/><ComponentB      objA={this.state.objA}}/>

step3
ComponentB 物件

        let _objA = this.props.objA        if (_objA instanceof ComponentA) {            _objA.funDoSomething()        }

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章