学习ReactJS。我创建了2条记录,我想在组件中显示但不知道如何操作。我有:
class ToyController < ApplicationController
def index
@users = User.all
render component: 'usersList', props: { users: @users }
end
end
和一个看似如下的组件:
var usersList = React.createClass({
propTypes: {
name: React.PropTypes.string,
age: React.PropTypes.number,
country: React.PropTypes.string,
},
render: function() {
return (
<div>
<h3>User List :D</h3>
<table style={{border: 1}}>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>{this.props.name}</td>
<td>{this.props.age}</td>
<td>{this.props.country}</td>
</tr>
</tbody>
</table>
</div>
);
}
});
如何在我的页面上显示模型数据?我在控制台中看到了我的数据的JS对象,但不知道如何让它们显示在表中。
答案 0 :(得分:1)
this.props.users
是对象数组,您需要遍历所有项目并从每个项目获取数据
var UsersList = React.createClass({
propTypes: {
users: React.PropTypes.array
},
render: function() {
var users = this.props.users.map(function (user) {
return <tr key={ user.id }>
<td>{ user.name }</td>
<td>{ user.age }</td>
<td>{ user.country }</td>
</tr>;
}, this);
return <div>
<h3>User List :D</h3>
<table style={{border: 1}}>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
</thead>
<tbody>
{ users }
</tbody>
</table>
</div>
}
});
var users = [
{ id: 1, name: 'name', age: 'age', country: 'country' },
{ id: 2, name: 'name-1', age: 'age-1', country: 'country-1' },
]
ReactDOM.render(
<UsersList users={ users } />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>