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
129 views
in Technique[技术] by (71.8m points)

javascript - Routing in Chrome Extension written in React

I want 2 pages in my Chrome extension. For example: first(default) page with list of users and second with actions for this user.

I want to display second page by clicking on user(ClickableListItem in my case). I use React and React Router. Here the component in which I have:

class Resents extends React.Component {
constructor(props) {
  super(props);
  this.handleOnClick = this.handleOnClick.bind(this);
}
handleOnClick() {
  console.log('navigate to next page');
  const path = '/description-view';
  browserHistory.push(path);
}
render() {
  const ClickableListItem = clickableEnhance(ListItem);
  return (
    <div>
      <List>
        <ClickableListItem
          primaryText="Donald Trump"
          leftAvatar={<Avatar src="img/some-guy.jpg" />}
          rightIcon={<ImageNavigateNext />}
          onClick={this.handleOnClick}
        />
      // some code missed for simplicity
      </List>
    </div>
  );
}
}

I also tried to wrap ClickableListItem into Link component(from react-router) but it does nothing.

Maybe the thing is that Chrome Extensions haven`t their browserHistory... But I don`t see any errors in console...

What can I do for routing with React?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

While you wouldn't want to use the browser (or hash) history for your extension, you could use a memory history. A memory history replicates the browser history, but maintains its own history stack.

import { createMemoryHistory } from 'history'
const history = createMemoryHistory()

For an extension with only two pages, using React Router is overkill. It would be simpler to maintain a value in state describing which "page" to render and use a switch or if/else statements to only render the correct page component.

render() {
  let page = null
  switch (this.state.page) {
  case 'home':
    page = <Home />
    break
  case 'user':
    page = <User />
    break
  }
  return page
}

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

...