我使用react-rails gem并将hash传递给react_component视图助手:
如何相当于
React.render(<BookApp books={BOOKS} />, document.getElementById('react-container'));
看起来像?
我假设
<div id="react-container">
<%= react_component('BookApp', books: '{BOOKS}') %>
</div>
但是这种方法并没有将哈希值作为道具传递。 我错过了什么?
book.js.jsx中的
var BOOKS = {
ulysses: {
slug: 'ulysses',
title: 'Ulysses',
body: 'YES BECAUSE HE NEVER DID...'
},
seizeTheDay: {
slug: 'seizeTheDay',
title: 'Seize the Day',
body: 'Seize the Day, first published in 1956...'
}
};
var CollapsibleBlock = React.createClass({
render: function() {
return(
<div className=
{this.props.toggleState ? 'open' :
'closed'}>
<h3 onClick=
{this.props
.toggleHandler
.bind(null, this.props.book.slug)}> // Uncaught TypeError: Cannot read property 'slug' of undefined
</h3>
<p>{this.props.book.body}</p>
</div>
);
}
});
var BookApp = React.createClass({
getInitialState: function() {
return {
ulysses: true,
seizeTheDay: false
}
},
// code omitted
render: function() {
return(
<div>
<h1>Toggable Content</h1>
<button onClick={this.toggleAll}>Toggle all</button> {}
<div>
{this.toggableBooks(this.props.books)}
</div>
</div>
)
}
});
在CollapsibleBlock中,我收到错误消息:
未捕获的TypeError:无法读取属性&#39; slug&#39;未定义的
我认为它是由于在视图页面上没有在react_component调用中传递的空Book-Hash引起的。
答案 0 :(得分:1)
你想给React组件一个JavaScript常量的名称,对吧?
那么如何将名称作为字符串传递:
<div id="react-container">
<%= react_component('BookApp', books_name: 'BOOKS') %>
</div>
然后,在组件中,使用字符串从window
:
var BookApp = React.createClass({
getInitialState: function() {
// Look up BOOKS by name:
var books = window[this.props.books_name]
// store the object as this.state.books
return {
ulysses: true,
seizeTheDay: false,
books: books,
}
},
// ...
}
答案 1 :(得分:0)
怎么样:
<div id="react-container">
<%= react_component('BookApp', booksJSON: @books.to_json) %>
</div>
并在组件中:
getInitialState: function () {
return {
books: (this.props.booksJSON.length > 0 ? JSON.parse(this.props.booksJSON) : []),
}
...
}