【问题标题】:Passing onselect value from menu component to another component reactjs将onselect值从菜单组件传递到另一个组件reactjs
【发布时间】:2019-02-23 02:03:39
【问题描述】:

我是新手,我一直在尝试实现一个我不确定的功能,我有一个组件可以呈现 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 就会转到映射函数,该函数将完成剩下的工作。我知道类别列表是硬编码的,现在,我只想在组件之间进行这种通信,我想将 id 从 menucat 组件传递给类似于产品列表中的变量的东西,而不是零喜欢{items.children[selected].children.map(item =&gt; (

【问题讨论】:

  • 你在你的应用程序中使用 redux 吗? React 没有办法将属性传递回组件树(这是设计使然)。组件之间的状态管理或组件树的备份都留给了 React 中的第三方库,其中 Redux 是最常见的。如果您对此不熟悉,我很乐意为您提供进一步帮助。

标签: javascript reactjs


【解决方案1】:

您需要向 MenuCat 添加一个“onSelect”属性以传递 ScrollMenu 的 onSelect 结果,然后在 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”函数,设置状态,然后可以在您的项目选择中使用该状态。

有意义吗?

【讨论】:

  • 非常感谢,确实很有道理
猜你喜欢
  • 2018-03-07
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多