Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

reactjs - Context in "stateless" component?

I have the following code in a component and I would like a stateless component to access this part of code:

Main component:

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/>;
}

Stateless:

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
    }
}
question from:https://stackoverflow.com/questions/35866066/context-in-stateless-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you have provided under your definition of "Stateless:" function is not what a Stateless function is. You have provided your action creator as a thunk. I assume you wanted to insert the code for your Client component instead. To access context in a stateless component, your Client component would do something like this (which is documented here)

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

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

export default Client

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...