【发布时间】:2020-09-17 17:19:31
【问题描述】:
我正在使用带有 react-rails gem 的 rails 5.1.7,在我的一个 erb 视图中使用 react_component() 助手有一个 react 组件我试图使 onChange 事件工作,但该函数没有响应反正。我应该能够看到控制台日志,但我没有看到它。
import React from "react"
import PropTypes from "prop-types"
class CardList extends React.Component {
constructor(props) {
super(props);
this.state = {
all_cards: this.props.all_cards,
orderBy: 'all',
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
console.log('change was made');
}
render () {
const allData = this.state.all_cards.map((card, index) => (
<div className="col-md-12">
{ card.category }
</div>
));
return (
<React.Fragment>
<label for="order">Order</label>
<select onChange={this.handleChange} name="order" id="order_filter">
<option value="element1">element1</option>
<option value="element2">element2</option>
</select>
{allData}
</React.Fragment>
);
}
}
CardList.propTypes = {
all_cards: PropTypes.array
};
export default CardList
在我看来,该组件被称为:
<%= react_component("cardlist", { all_cards: @all_cards }, {prerender: true}) %>
如果我尝试将以下内容添加到 serverRendering.js 文件中:
ReactRailsUJS.mountComponents()
我在组件应该挂载的页面中收到此错误:
ExecJS::ProgramError in Cards#index
ReferenceError: document is not defined
我也尝试用<div> 标记替换React.Fragment 或更改handleChange 中的状态
【问题讨论】:
-
您的代码可以正常工作,问题可能是您如何使用 react_component 调用此代码。尝试在您的功能中执行其他操作,例如警报或重定向。我不知道这个 react_component 是如何工作的,但可能是一个限制。
标签: ruby-on-rails reactjs react-rails