简体   繁体   English

如何将道具传递给 Reactjs 中的子组件

[英]How to pass props to subcomponent in Reactjs

I am attempting to pass props from a parent component function to a child in React without any luck.我试图将来自父组件 function 的道具传递给 React 中的孩子,但没有任何运气。 I am utilizing the React Data Table Component 's filtering functionality .我正在使用React 数据表组件的过滤功能 The example documentation in Storybook is great, however I want to change the search box into a list of tags, that when clicked, will filter the data table just the same. Storybook 中的示例文档很棒,但是我想将搜索框更改为标签列表,单击该列表时,将过滤数据表。

The data I'm trying to parse into individual "tags" is structured like this:我试图解析成单个“标签”的数据结构如下:

  [{"id":"09090","first_name":"Cynthia","last_name":"McDonald","email":"email1@gmail.com","profile_url":"https:myprofile.com/1","types":["professor","science"]},
{"id":"03030","first_name":"Ryan","last_name":"Burke","email":"email2@gmail.com","profile_url":"https://myprofile.com/2","types":["student","science"]},
{"id":"05050","first_name":"Stewart","last_name":"Hook","email":"email3@gmail.com","profile_url":"https://myprofile.com/3","types":["professor","math"]}]

I am trying to create a unique tag list of the "types" attribute that acts as a filter onClick instead of onChange, just like the original search textbox example.我正在尝试创建“类型”属性的唯一标记列表,该列表充当过滤器 onClick 而不是 onChange,就像原始搜索文本框示例一样。 So based on the sample data, we would end up with tags for professor, science, student, and math.因此,根据样本数据,我们最终会得到教授、科学、学生和数学的标签。

If you look at the code in Storybook, more specifically, line 45:如果您查看 Storybook 中的代码,更具体地说,第 45 行:

const subHeaderComponentMemo = React.useMemo(() => 
<Filter onFilter={value => setFilterText(value)} />, []);

My data is loaded via an API call and I am trying to pass that data to the subHeaderComponentMemo with props, ie,我的数据是通过 API 调用加载的,我正在尝试使用道具将该数据传递给 subHeaderComponentMemo,即

const subHeaderComponentMemo = React.useMemo(() => 
<Filter data={people} onFilter={value => setFilterText(value)} />, []);

I am then trying to receive and loop through that data on line 20 and am replacing most of that code so that it will render the unique tags from the types attribute of the data.然后,我尝试在第 20 行接收并循环遍历该数据,并替换大部分代码,以便它将呈现来自数据类型属性的唯一标签。

Storybook code:故事书代码:

const Filter = ({ onFilter }) => (  
<TextField id="search" type="search" role="search" placeholder="Search Title" onChange={e => onFilter(e.target.value)} />
);

My failed code我失败的代码

const Filter = ({props, onFilter }) => {
  // Get a unique array of types
  const types = [...new Set(props.types.map(type => type))];

  return types.map(type => (
    <span
      className="badge badge-primary"
      onClick={() => onFilter({ type })}
      onKeyDown={() => onFilter({ type })}
      tabIndex="0"
      role="button"
    >
      {type}
    </span>
  ));
};

This is of course resulting in an epic fail.这当然会导致史诗般的失败。 The module isn't even displaying.该模块甚至没有显示。

I'm new to React, so any insight/help would be greatly appreciated.我是 React 的新手,所以任何见解/帮助将不胜感激。

Updated code based on feedback根据反馈更新代码

const Filter = ({ data, onFilter }) => {
  console.dir(data);
  if (data.length === 0) {
    return <div>No data</div>;
  }

  const types = [...new Set(data.types.map(type => type))];

  return (
    <>
      {types.map(type => (
        <span
          className="badge badge-primary"
          onClick={() => onFilter({ type })}
          onKeyDown={() => onFilter({ type })}
          tabIndex="0"
          role="button"
        >
          {type}
        </span>
      ))}
      ;
    </>
  );
};

One of the errors I got when I made the changes was "cannot read property of 'map' undefined", which I equated to the fact that this component may be rendering before the data gets there and it is empty.我进行更改时遇到的错误之一是“无法读取 'map' undefined 的属性”,我将其等同于该组件可能在数据到达那里并且它是空的之前呈现的事实。 So I added an if with a return in case this happens.所以我添加了一个 if 和 return 以防发生这种情况。

I also rewrote the return the statement in Filter based on the feedback because it did look like it would loop and try to render a new component for each iteration.我还根据反馈重写了 Filter 中的 return 语句,因为它看起来确实会循环并尝试为每次迭代呈现一个新组件。

However, the issue still stands with the data not being present.但是,问题仍然存在,因为数据不存在。 The table is now loading with the data, but this component is just returning the "No data" div as if nothing ever happened.该表现在正在加载数据,但该组件只是返回“无数据”div,就好像什么都没发生过一样。 I'm not sure if this is due to the useMemo hook or what.我不确定这是由于 useMemo 钩子还是什么。 Besides that, no errors.除此之外,没有错误。

Thank you for your time and feedback.感谢您的时间和反馈。

Another update另一个更新

UseMemo needed the prop to be a dependency in its array... I'm finally seeing data when I console.log it. UseMemo 需要道具成为其数组中的依赖项......当我 console.log 它时,我终于看到了数据。

const subHeaderComponentMemo = useMemo(
    () => <Filter data={people} onFilter={value => setFilterText(value)} />,
    [people]
  );

However, I'm getting the 'map' undefined error again, as if my data is not in the structure I expect it to be in. I have not changed it and this is the code I'm using to try to access it (as shared before):但是,我再次收到“地图”未定义错误,好像我的数据不在我期望的结构中。我没有更改它,这是我用来尝试访问它的代码(如前所述):

  const types = [...new Set(data.types.map(type => type))];

Thanks again everyone... getting closer!再次感谢大家......越来越近了!

you should rewrite you component signature to match the one you are trying to use您应该重写组件签名以匹配您尝试使用的签名

const Filter = ({props, onFilter }) => // you are expecting a props name props

<Filter data={people} onFilter={value => setFilterText(value)} />, []); // you are passing data and setFilterText 

so you should change it to所以你应该把它改成

const Filter = ({data, onFilter }) => const Filter = ({data, onFilter }) =>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM