我正在为表中的行项目创建react元素。我正在使用React-rails来做这件事,并且遇到了一些奇怪的行为。
我的数据库中有一条记录,而我的react组件列出了重复的条目。这就是在DOM中呈现的内容。
<div class="table-responsive">
<div data-react-class="questions/QuestionLineItem" data-react-props="{"prompt":"What year was the NFL founded?","uuid":"f85c2f85-95d8-4037-963f-d1503b24123b"}" data-hydrate="t">
<tr><td>f85c2f85-95d8-4037-963f-d1503b24123b</td><td>What year was the NFL founded?</td></tr>
</div>
<table class="table table-striped table-sm">
<thead>
<tr>
<th>UUID</th>
<th>Question</th>
</tr>
</thead>
<tbody>
<tr data-reactroot=""><td>f85c2f85-95d8-4037-963f-d1503b24123b</td><td>What year was the NFL founded?</td></tr>
</tbody>
</table>
</div>一条记录被正确地呈现到表中,但另一条记录浮动在顶部,而不是嵌套在表中。我的item组件非常简单。
import React from "react";
import PropTypes from "prop-types";
class QuestionLineItem extends React.Component {
render() {
return (
<tr>
<td>{this.props.uuid}</td>
<td>{this.props.prompt}</td>
</tr>
);
}
}
QuestionLineItem.propTypes = {
prompt: PropTypes.string
};
export default QuestionLineItem;该视图只是一个简单的表,它遍历活动记录集合中的所有项。
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>UUID</th>
<th>Question</th>
</tr>
</thead>
<tbody>
<% @questions.each do |q| %>
<%= react_component('questions/QuestionLineItem', { prompt: q.prompt, uuid: q.uuid }, { prerender: true} ) %>
<% end %>
</tbody>
</table>
</div>有人能解释这种行为吗?
问题控制器只包含一个索引操作。
class QuestionsController < ApplicationsController
def index
@questions = Question.all
end
end

发布于 2018-12-03 09:32:29
您是否尝试过将<React.Fragment>添加到React组件的输出中?它看起来像这样:
class QuestionLineItem extends React.Component {
render() {
return (
<React.Fragment>
<tr>
<td>{this.props.uuid}</td>
<td>{this.props.prompt}</td>
</tr>
</React.Fragment>
);
}
}作为参考,您可以在此处阅读有关React.Fragments more here的信息
https://stackoverflow.com/questions/53583913
复制相似问题