[英]Converting contents from html to ReactJS file
如果問題令人困惑,我們深表歉意。 基本上我有這個html代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Gentle Introduction</title>
<script
src="https://rawgit.com/flatiron/director/master/build/director.min.js">
</script>
<script>
var author = function () { console.log("author"); };
var books = function () { console.log("books"); };
var viewBook = function (bookId) {
console.log("viewBook: bookId is populated: " + bookId);
};
var routes = {
'/author': author,
'/books': [books, function() {
console.log("An inline route handler.");
}],
'/books/view/:bookId': viewBook
};
var router = Router(routes);
router.init();
</script>
</head>
<body>
<ul>
<li><a href="#/author">#/author</a></li>
<li><a href="#/books">#/books</a></li>
<li><a href="#/books/view/1">#/books/view/1</a></li>
</ul>
</body>
</html>
顯然在.html文件中。 我想將其更改為.js文件,以便可以在js中放入html,以便在單擊不同鏈接時,路由/返回的內容不同。
我真的不知道如何直接將其放入javascript文件中,然后使路由器工作。 這是html文件來自https://github.com/flatiron/director#client-side-routing的位置 ,我正在嘗試使用此Flatiron / director路由器。
任何幫助將是巨大的!
我能夠使其與react和jsx一起工作,而外部的路由代碼也可以自身響應。
與es6 / es2015一起編寫
app.js
const author = () => { console.log("author"); };
const books = () => { console.log("books"); };
const viewBook = (bookId) => { console.log("viewBook: bookId is populated: " + bookId); };
const routes = {
'/author': author,
'/books': [books, () => { console.log("An inline route handler."); }],
'/books/view/:bookId': viewBook
};
const router = Router(routes);
router.init();
class SampleRouting extends React.Component {
render() {
return (
<ul>
<li><a href="#/author">#/author</a></li>
<li><a href="#/books">#/books</a></li>
<li><a href ="#/books/view/1">#/books/view/1</a></li>
</ul>
)
}
}
React.render( <SampleRouting/> , document.getElementById('root'));
index.html
<div id="root"></div>
范例: http : //s.codepen.io/oobgam/debug/vNoogO
_edit app.js以反映狀態和頁面標題的更新
class App extends React.Component {
constructor(props) {
super(props);
this.state = { currentPage: 'author' }
}
componentDidMount() {
const author = () => { this.setState({currentPage: 'author'}) };
const books = () => { this.setState({currentPage: 'Books'}); };
const viewBook = (bookId) => { this.setState({currentPage: 'Book ' + bookId }); };
const routes = {
'/author': author,
'/books': books,
'/books/view/:bookId': viewBook
};
const router = Router(routes);
router.init();
}
render() {
return (
<div>
<h1>{ this.state.currentPage }</h1>
<SampleRouting />
</div>
);
}
}
// stateless function
const SampleRouting = () => {
return (
<ul>
<li><a href="#/author">#/author</a></li>
<li><a href="#/books">#/books</a></li>
<li><a href ="#/books/view/1">#/books/view/1</a></li>
< /ul>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.