使用React PropTypes

时间:2017-01-30 20:35:43

标签: javascript reactjs auth0

如何使用React PropTypes添加Auth0?

index.js

import App from '../components/App';
import WelcomeRoute from './Welcome';
import SettingsRoute from './Settings';
import CampaignRoute from './Campaign';

export default {
  path: '/',
  component: App,
  indexRoute: WelcomeRoute,
  childRoutes: [
    SettingsRoute,
    CampaignRoute
  ]
};

App.js

import React, {PropTypes} from 'react';
import Header from '../../components/Header';
import MessagesStack from '../../components/MessagesStack'

const App = ({children}) => (
  <div>
    <Header />
    <section className="ui main container">
      <MessagesStack />
      {children}
    </section>
  </div>
);

App.propTypes = {
  children: PropTypes.element.isRequired
};

export default App;

来自Auth0的样本显示:

App.js

import React, {Component} from 'react';
import {Router, Route, browserHistory} from 'react-router';
import {requireAuth} from '../auth';
import Site from './Site';
import Home from './Home';
import Login from './Login';
import EditProfile from './EditProfile';

class App extends Component {
  render() {
    return (
      <Router history={browserHistory}>
        <Route component={Site}>
          <Route path="/" component={Home} />
          <Route path="/login" component={Login} />
          <Route onEnter={requireAuth}>
            {/* Place all authenticated routes here */}
            <Route path="/profile/edit" component={EditProfile} />
          </Route>
        </Route>
      </Router>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:0)

如果您的组件依赖于Auth0用户配置文件和/或AuthService,您可以执行以下操作

import React, { PropTypes as T } from 'react'
...
import AuthService from 'utils/AuthService'
...

export class ProfileEdit extends React.Component {
  static propTypes = {
    profile: T.object,
    auth: T.instanceOf(AuthService)
  }

.
.
.
}   

以下是https://github.com/auth0-samples/auth0-react-sample/blob/master/04-User-Profile的完整示例 在这里你可以看到PropTypes如何用于Auth0用户配置文件和AuthService https://github.com/auth0-samples/auth0-react-sample/blob/master/04-User-Profile/src/components/Profile/ProfileEdit.js#L8