2016-03-08 13 views
12

Ben bir bileşeni aşağıdaki kodu var ve bu kod parçasını erişmek için vatansız bileşeni istiyorum:"Vatansız" bileşenindeki içerik?

Ana bileşen:

function createApp(store, communityIds) { 
const App = React.createClass({ 

    childContextTypes: { 
     localizedString: React.PropTypes.func, 
    }, 

    getChildContext: function() { 
     return { 
      localizedString: function(key, fallback) { 
       return getKey(key, fallback); 
      }, 
     }; 
    }, 

    render: function() { 
     return (
      <Provider store={store}> 
       <Client communityIds={communityIds}/> 
      </Provider> 
     ); 
    }, 
}); 

return <App/>; 
} 

Vatansız:

export default() => (dispatch, getState) => { 
const state = getState(); 

const token = state.user.get('token'); 

if (!token) { 
    throw new Error('test'); // this.context.localizedString does not work 
} 
} 

herhangi seviniriz ipuçları, saygılarımla!

cevap

14

"Durum bilgisi:" tanımınız altında sağladığınız işlev, Durumsuz bir işlevin işlevi değildir. Aksiyon oluşturucunuzu bir thunk olarak sağladınız. Bunun yerine, sizin için Müşteri bileşenini eklemek istediniz. devletsiz bileşeninde bağlamı erişmek için, Müşteri bileşen (here belgelenmiştir) böyle bir şey

const Client = (props, context) => { 
    return <div >{context.localizedString("someKey", "someFallback")} </div> 
} 

Client.contextTypes = { 
    localizedString: React.PropTypes.func 
} 

export default Client 
1

Başka bir çözüm kendi kendine çağıran fonksiyonudur yapacağını:

export default (Component=>(
    Component.contextTypes = { 
    localizedString: React.PropTypes.func 
    }) && Component 
)((props, context)=>{ 
    return <div>{context.localizedString("someKey", "someFallback")}</div> 
}) 

Yoksa contextTypes tanımlarsanız Yeniden kullanmak için ayrı ayrı aşağıdakileri yapabilirsiniz:

//addContextTypes.js 
export default function(Component){ 
    return (Component.contextTypes = { 
    localizedString: React.PropTypes.func 
    }) && Component 
} 

//component.jsx 
import addContextTypes from './addContextTypes' 
export default addContextTypes((props, context)=>{ 
    return <div>{context.localizedString("someKey", "someFallback")}</div> 
}) 
İlgili konular