我的组件中有以下代码,我希望无状态组件能够访问这部分代码:
主要成分:
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/>;
}
无状态:
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
}
}
最佳答案
您在“无状态:”函数的定义下提供的内容并不是无状态函数。您已将 Action 创建者作为 thunk 提供。我假设您想插入客户端组件的代码。要访问无状态组件中的上下文,您的客户端组件将执行类似的操作(记录在 here 中)
const Client = (props, context) => {
return <div >{context.localizedString("someKey", "someFallback")} </div>
}
Client.contextTypes = {
localizedString: React.PropTypes.func
}
export default Client
关于reactjs - "stateless"组件中的上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35866066/