将功能作为道具传递给反应中的组件

时间:2020-09-25 21:16:12

标签: javascript reactjs

在此Reactjs代码中,除了组件代码(filter.js)外,我在app.js中还有主代码,我只想在sort上使用sortProducts和filterProducts函数打印控制台中DDL选择选项的值,方法是将它们作为道具传递给滤镜组件。 我花了很多时间,但我不知道为什么我更改控制台后仍然保持空白,看不到onchange函数。你能帮忙吗?

App.js代码:

    import React from "react";
import data from "./Mobilesdata.json";
import Products from "./Components/Products";
import Filter from "./Components/Filter";
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      products: data.products,
      size: "",
      sort: "",
    };
  }
  sortProducts(event) {
    console.log(event.target.value);
  }

  filterProducts(event) {
    console.log(event.target.value);
  }

  render() {
    return (
      <div className="grid-container">
        <header>
          <a href="/">React Shopping Cart</a>
        </header>
        <main>
          <div className="content">
            <div className="main">
              <Filter count={this.state.products.length}>
                size={this.state.size}
                sort={this.state.sort}
                sortProducts={this.sortProducts}
                filterProducts={this.filterProducts}
              </Filter>
              <Products products={this.state.products}></Products>
            </div>
            <div className="sidebar">cart Items</div>
          </div>
        </main>
        <footer>All right Reserved </footer>
      </div>
    );
  }
}

export default App;

Filter.js代码:

import React, { Component } from "react";

export default class Filter extends Component {
  render() {
    return (
      <div className="filter">
        <div className="filter-result">{this.props.count} products</div>
        <div className="filter-sort">
          Order{""}
          <select
            value={this.props.sort}
            onChange={this.props.sortProducts}
          >
            <option value="latest">Latest</option>
            <option value="lowest">Lowest</option>
            <option value="highest">Highest</option>
          </select>
        </div>
        <div className="filter-size">
          Filter{""}
          <select
            value={this.props.size}
            onChange={this.props.filterProducts}
          >
            <option value="All">All</option>
            <option value="Iphone">Iphone</option>
            <option value="Huawei">Huawei</option>
            <option value="Samsung">Samsung</option>
          </select>
        </div>
      </div>
    );
  }
}


0 个答案:

没有答案