onChange函数不适用于带有react-rails的erb中的react组件

问题描述

我正在将rails 5.1.7与react-rails gem一起使用,在我的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

我还尝试用React.Fragment标签替换<div>或更改handleChange中的状态

解决方法

在元素上尝试使用onInput代替onChange标签,这可能会按照您想要的方式工作。

,

将组件安装到.erb上的方式可能有问题。我创建了一个repo来演示如何在您的项目中正确设置react-rails。要处理搜索/过滤器功能,请查看此commit

简而言之,

  1. 确保将正确的组件名称传递到react_components上。就我而言,我通过了App作为主要组成部分。参见here
  2. 确保自动导出所有组件。在这种情况下,请按here所示使用react_ujs。我的组件文件夹名称是components,这就是为什么我使用const componentRequireContext = require.context('components',true);