2015-08-18 10 views
15

Come ti scrivere i childContextTypes degli oggetti in ES6?childContextTypes in ES6

var A = React.createClass({ 

    childContextTypes: { 
     name: React.PropTypes.string.isRequired 
    }, 

    getChildContext: function() { 
     return { name: "Jonas" }; 
    }, 

    render: function() { 
     return <B />; 
    } 
}); 
+0

Non sarebbe affatto. 'class'es non supporta membri statici. Assegnalo esplicitamente dopo la dichiarazione, o usa 'Object.assign' – Bergi

+0

Uh amico mio, ho bisogno di un po 'più di aiuto. Puoi mostrarmi? –

+1

Guida [this] (http://stackoverflow.com/q/29433130/1048572)? Non sono sicuro se si tratta di un duplicato – Bergi

risposta

0

La soluzione era quella di spostare "childContextTypes" fuori dalla classe:

classe; { ,, .}

childContextTypes() {..}

O aspettare che ES7 di avere proprietà statiche.

20

Dal momento che si sta utilizzando Babel in ogni caso, è possibile utilizzare static (ES7) nel codice come questo:

export default class A extends React.Component { 

    static childContextTypes = { 
    name: React.PropTypes.string, 
    } 

    getChildContext() { 
    return { name: "Jonas" } 
    } 

    render() { 
    return <B /> 
    } 
} 

Maggiori informazioni: React on ES6+

+0

La pagina del blog more-info è trasferito a https://babeljs.io/blog/2015/06/07/react-on-es6-plus – jakewins

+0

Grazie jakewins. Aggiornato il collegamento di conseguenza. – cutemachine

10

Il problema è che childContextTypes deve essere definito sulla "classe", che è ciò che fa static. Così queste due soluzioni sembrano funzionare:

class A extends React.Component { 
    constructor() { 
    super(...arguments); 

    this.constructor.childContextTypes = { 
     name: React.PropTypes.string.isRequired 
    }; 
    } 
} 

O

class A extends React.Component { 

} 

A.childContextTypes = { 
    name: React.PropTypes.string.isRequired 
}; 
0

provare questo:

import React, { PropTypes } from 'react'; 
 

 
export default class Grandparent extends React.Component { 
 
    static childContextTypes = { 
 
    getUser: PropTypes.func 
 
    }; 
 

 
    getChildContext() { 
 
    return { 
 
     getUser:() => ({ name: 'Bob' }) 
 
    }; 
 
    } 
 

 
    render() { 
 
    return <Parent />; 
 
    } 
 
} 
 

 
class Parent extends React.Component { 
 
    render() { 
 
    return <Child />; 
 
    } 
 
} 
 

 
class Child extends React.Component { 
 
    static contextTypes = { 
 
    getUser: PropTypes.func.isRequired 
 
    }; 
 

 
    render() { 
 
    const user = this.context.getUser(); 
 
    return <p>Hello {user.name}!</p>; 
 
    } 
 
}

sorgente sotto forma di codice qui: React ES6 Context

+0

C'è un errore di sintassi in 'getUser:() => ({name: 'Bob'})' –

-1

Se si utilizza CoffeeScript ...

cambiamento

childContextTypes: 

a

@childContextTypes: