簡體   English   中英

onChange 函數在帶有 react-rails 的 erb 中的反應組件中不起作用

[英]onChange function not working in a react component in a erb with react-rails

我正在將 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

我還嘗試用<div>標簽替換React.Fragment或更改handleChange的狀態

在元素上嘗試使用onInput而不是onChange標簽,這可能會按照您想要的方式工作。

組件安裝到.erb的方式可能存在問題。 我創建了一個repo來演示如何在您的項目中正確設置react-rails 要處理搜索/過濾功能,請查看此提交

簡而言之,

  1. 確保您將組件的正確名稱傳遞給react_components 就我而言,我通過App作為主要組件。 這里
  2. 確保自動導出所有組件。 在這種情況下,使用react_ujs如圖所示這里 我的組件文件夾名稱是components這就是為什么我使用const componentRequireContext = require.context('components', true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM