說好補上就補上!
先加上rails books_controller.rb的home...
def home
@books = {books: Book.includes(:author).as_json(methods: [:author_name])}
end
也在routes.rb加上root
root "books#home"
然後補上books/home.html.erb的view~
<%= react_component("ReadingListApp", props: @books, prerender: false) %>
(不是說沒有Rails了嗎!!!???
沒辦法 忘了加上去了,要寫才想到RRRRRR
import React from 'react';
import ReactOnRails from 'react-on-rails';
import ReadingList from '../containers/ReadingList';
const ReadingListApp = (props) => {
return <ReadingList {...props} />
};
ReactOnRails.register({ ReadingListApp });
import React, { PropTypes } from 'react';
import ReadingListWidget from '../components/ReadingListWidget';
let propTypes = {
books: PropTypes.array.isRequired,
};
class ReadingList extends React.Component {
constructor(props, context) {
super(props, context);
console.log(props)
this.state = {
books: this.props.books
};
}
updateBooks(books) {
this.setState({books})
}
render() {
return (
<div>
<ReadingListWidget books={this.state.books} updateBooks={e => this.updateBooks(e)} />
</div>
);
}
}
ReadingList.propTypes = propTypes;
export default ReadingList;
import React, { PropTypes } from 'react';
import Book from './Book';
const propTypes = {
updateBooks: PropTypes.func.isRequired,
books: PropTypes.array.isRequired,
};
class ReadingListWidget extends React.Component {
constructor(props){
super(props);
}
handleChange(e) {
const books = e.target.value;
this.props.updateBooks(books);
}
render() {
const { books } = this.props;
const bookComponents = books.map((book, index) => {
return <Book key={index} { ...book}/>
});
return (
<div className="container">
<h3>
Reading List
</h3>
{bookComponents}
<hr />
</div>
);
}
}
ReadingListWidget.propTypes = propTypes;
export default ReadingListWidget;
import React, { PropTypes } from 'react';
const propTypes = {
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
status: PropTypes.string.isRequired,
author_id: PropTypes.number.isRequired,
author_name: PropTypes.string.isRequired
}
class Book extends React.Component {
constructor(props){
super(props);
}
render() {
const {id, name, status, author_name} = this.props;
return (
<div className="row">
<div className="col-md-1">{id}</div>
<div className="col-md-2">{status}</div>
<div className="col-md-3">{name}</div>
<div className="col-md-3">{author_name}</div>
<div className="col-md-3">{author_name}</div>
</div>
);
}
}
Book.propTypes = propTypes;
export default Book;
先寫個不負責任沒有功能只有UI的React,
明天把功能補上並加上講解,
Sorrrrry阿各位,今天環境有點變過,所以不是很適應。
上github可以看到code~
Rails > Model > Book 部分要再補上
delegate :name, to: :author, prefix: true
或者
def author_name
author.name
end
才能正確執行 books#home
https://github.com/josephMG/itHelpRRRR/blob/master/app/models/book.rb#L6
對! 我Github有,但是這裡忘了說要補上了@@
感謝你協助提醒~