2017-04-26 84 views
2

React可以将原型分配给子组件,而不是传递槽道具? 我们可以做这样的事情:我们可以给儿童组件分配原型吗?

import React, { Component } from 'react' 
import Child from './Child' 

export default class Parent extends Component { 
    constructor(){ 
    super() 
    this.parentMethod = this.parentMethod.bind(this) 
    } 
    parentMethod() { 
    // this method is going to be assigned to Child 
    console.log('I am invoked from child') 
    } 

    render() { 
     Child.prototype = this.parentMethod 
     // now 
     return <Child /> 
    } 

} 


//Child.js 

import React, { Component } from 'react' 
export default class Child extends Component { 
    constructor() { 
    super() 
    } 

    handleButton() { 
     this.parentMethod() 
    } 
    render() { 
     return (
     <button onClick={this.handleButton.bind(this)} > click </button> 
    ) 
    } 
} 

我不是很肯定,如果我做错了什么,但代码的作品?

+0

您有几种选择在这里 - 家长可以通过两种道具传递函数来从子组件调用。或者,如果您有几个组件可能会或可能不是父级的孩子,但仍然需要该功能 - 您可以创建更高级别的组件(HOC)。 简而言之,HOC需要一个组件并返回一个添加了功能的新组件。 https://egghead.io/lessons/react-react-fundamentals-higher-order-components-replaces-mixins https://facebook.github.io/react/docs/higher-order-components.html –

回答

0

首先,更改对象的.prototype属性不会设置其实际原型。设置对象原型的唯一可靠方法是Object.setPrototypeOf函数。所以你试图做的方式将无法可靠地工作。

但是,即使你正在做正确的方式,你真的不应该这样做呢:

由于ES6 class ES超过原型只是语法糖,你应该做到这一点。你的React组件依赖于Component原型,以确保他们的生命期方法在正确的时间被调用,并且它们的道具在对象构建时被正确处理。试图改变React组件的原型只会搞乱它,并使其停止像一个真正的React组件。

如果您希望您的子组件能够访问其父组件的方法,则正确的方法是将该方法作为道具传递。

例如:

export default class Parent extends Component { 
    // React component constructors receive props 
    constructor (props){ 
    super(props) 
    this.parentMethod = this.parentMethod.bind(this) 
    } 
    parentMethod() { 
    // this method is going to be assigned to Child 
    console.log('I am invoked from child') 
    } 

    render() { 
     return <Child parentCallback={this.parentMethod} /> 
    } 

} 


//Child.js 

import React, { Component } from 'react' 
export default class Child extends Component { 
    //no constructor needed if you just call super() 

    render() { 
     return (
     <button onClick={this.props.parentCallback} > click </button> 
    ) 
    } 
} 

从理论上说,你可以有你的孩子组件extend你的父组件,但是这将是糟糕的面向对象设计,并且有很多很好的论据为什么you should avoid using extends-based inheritance