从菜单组件传递onselect值到另一个组件reactjs

时间:2019-02-23 02:03:40

标签: javascript reactjs

我是新来的反应者,我一直在尝试实现不确定的功能,我有一个呈现JSON文件并显示名为“产品列表”的产品的组件,另一个名为“人”的组件是用来显示产品项目,两者都工作正常,但是第三个名为menucat的组件包括来自https://www.npmjs.com/package/react-horizontal-scrolling-menu的滚动菜单,菜单组件的onselect函数在选择时返回一个id编号,我想将该编号传递给产品列表中的映射功能。

产品列表

import React from "react";
import Person from "./Person";MenuCat";
import MenuCat, {a, onSelect, selected}  from "../components/


class ProductList extends React.Component {
  state = {
    error: null,
    isLoaded: false,
    items: []
  };

  componentDidMount() {
    fetch("items.json")
      .then(res => res.json())
      .then(
        result => {
          this.setState({
            isLoaded: true,
            items: result
          });
        },

        error => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
  }


  render() {

    const { error, isLoaded, items } = this.state;
    if (error) {
      return (
        <div>
          Error:{" "}
          {error.message  }
          {console.log("check 1:", items)}
        </div>
      );
    } else if (!isLoaded) {
      return (
        <div>
          <img
            src="loading.gif"
            alt="loading"
            height="100"
          />
        </div>
      );
    } else { 
       return (
        <div>
          <MenuCat />
          <div className="row">
            {items.children[0].children.map(item => (
              <Person
                className="person"
                Key={item.name}
                Title={item.name}
                imgSrc={item.image_url}
              >

                {item.base_price}  
              </Person>
            ))}
          </div>
        </div>
      );
     }
  }
}

和menuCat组件如下所示

import React, { Component } from "react";
import ScrollMenu from "react-horizontal-scrolling-menu";
import "../menu.css";

// list of items


const list  = [
  { name: "category1" , id : 0},
  { name: "category2" , id : 1},
  { name: "category3" , id : 2},
  { name: "category4" , id : 3},
  { name: "category5" , id : 4},
  { name: "category6" , id : 5},
  { name: "category7" , id : 6},

];


// One item component
// selected prop will be passed
const MenuItem = ({ text, selected }) => {
  return <div className="menu-item">{text}</div>;
};

// All items component
// Important! add unique key
export const Menu = list =>
  list.map(el => {
    const { name } = el;
    const { id } = el;

    return <MenuItem text={name} key={id} />;
  });

const Arrow = ({ text, className }) => {
  return <div className={className}>{text}</div>;
};

const ArrowLeft = Arrow({ text: "<", className: "arrow-prev" });
const ArrowRight = Arrow({ text: ">", className: "arrow-next" });

export class Menucat extends Component {
  state = {
    selected: "0"
  };

  onSelect = key => {
    console.log(`onSelect: ${key}`);
    this.setState({ selected: key});
  };

  render() {
    const { selected  } = this.state;
     // Create menu from items
    const menu = Menu(list, selected);

    return (
      <div className="App">
        <ScrollMenu
          data={menu}
          arrowLeft={ArrowLeft}
          arrowRight={ArrowRight}
          selected={selected}
           onSelect={this.onSelect}
        />
      </div>
    );
  }
}

 export default Menucat;

我希望添加从onselect函数生成的ID而不是

中的0
            {items.children[0].children.map(item => (

,以便每当用户单击类别项目时,该类别的ID就会转到映射函数,其余的将由映射函数完成。我知道类别列表是硬编码的,现在,我只想在组件之间进行这种通信,我想将menucat组件的id传递给类似于产品列表中的变量的变量,该变量可以而不是零像{items.children[selected].children.map(item => (

1 个答案:

答案 0 :(得分:0)

您将要向MenuCat添加“ onSelect”属性以通过ScrollMenu的onSelect结果,然后在ProductList中添加状态值以存储选定的键。像这样的东西:

ProductList

import React from "react";
import Person from "./Person";MenuCat";
import MenuCat, {a, onSelect, selected}  from "../components/


class ProductList extends React.Component {
    state = {
        error: null,
        isLoaded: false,
        items: [],
        selected: 0,
    };

    componentDidMount() {
        fetch("items.json")
            .then(res => res.json())
            .then(
                result => {
                    this.setState({
                        isLoaded: true,
                        items: result
                    });
                },

                error => {
                    this.setState({
                        isLoaded: true,
                        error
                    });
                }
            );
    }

    constructor(props) {
        super(props);
        this.onSelect = this.onSelect.bind(this);
    }

    onSelect(key) {
        this.setState({selected: key});
    }


    render() {

        const { error, isLoaded, items } = this.state;
        if (error) {
            return (
                <div>
                Error:{" "}
            {error.message  }
            {console.log("check 1:", items)}
        </div>
        );
        } else if (!isLoaded) {
            return (
                <div>
                <img
            src="loading.gif"
            alt="loading"
            height="100"
                />
                </div>
        );
        } else {
            return (
                <div>
                <MenuCat onSelect={this.onSelect} />
                <div className="row">
                {items.children[this.state.selected].children.map(item => (
                    <Person
            className="person"
            Key={item.name}
            Title={item.name}
            imgSrc={item.image_url}
        >

            {item.base_price}
        </Person>
        ))}
        </div>
            </div>
        );
        }
    }
}

和MenuCat之类的

import React, { Component } from "react";
import ScrollMenu from "react-horizontal-scrolling-menu";
import "../menu.css";

// list of items


const list  = [
    { name: "category1" , id : 0},
    { name: "category2" , id : 1},
    { name: "category3" , id : 2},
    { name: "category4" , id : 3},
    { name: "category5" , id : 4},
    { name: "category6" , id : 5},
    { name: "category7" , id : 6},

];


// One item component
// selected prop will be passed
const MenuItem = ({ text, selected }) => {
    return <div className="menu-item">{text}</div>;
};

// All items component
// Important! add unique key
export const Menu = list =>
    list.map(el => {
        const { name } = el;
        const { id } = el;

        return <MenuItem text={name} key={id} />;
    });

const Arrow = ({ text, className }) => {
    return <div className={className}>{text}</div>;
};

const ArrowLeft = Arrow({ text: "<", className: "arrow-prev" });
const ArrowRight = Arrow({ text: ">", className: "arrow-next" });

export class Menucat extends Component {
    state = {
        selected: "0"
    };

    onSelect = key => {
        console.log(`onSelect: ${key}`);
        this.setState({ selected: key});
        this.props.onSelect(key);
    };

    render() {
        const { selected  } = this.state;
        // Create menu from items
        const menu = Menu(list, selected);

        return (
            <div className="App">
            <ScrollMenu
        data={menu}
        arrowLeft={ArrowLeft}
        arrowRight={ArrowRight}
        selected={selected}
        onSelect={this.onSelect}
        />
        </div>
    );
    }
}

export default Menucat;

您将一个“ onSelect”功能传递给menucat,当选择该项目时menucat对其进行调用,然后返回到ProductList,然后运行其“ onSelect”功能,并设置可用于您选择项目的状态。

有意义吗?