简体   繁体   English

reactjs-将不同的道具传递给同一组件

[英]reactjs - pass different props to the same component

Hello I have a challenge figuring out how I can extend and add extra props to the page. 您好,我在确定如何扩展页面以及向页面添加其他道具方面遇到了挑战。 This below code snippet works just fine, and it populates basic text. 下面的代码片段可以正常工作,并填充基本文本。

import React from 'react';
import { Text } from '@whatever-library';

const SomeComponent = (props) => (
  <div>
    <Text field={props.fields.heading} />
  </div>
);

So now I would like to add data from an external API to render in this same component. 所以现在我想从外部API添加数据以在同一组件中进行渲染。 Below is a snippet from another .js file that is working and displaying content from the api fetch, how can I combine those two 以下是另一个.js文件的代码段,该文件正在工作并显示api提取中的内容,我该如何结合这两个

    class apiFetch extends SomeComponent {
      constructor(props) {
        super(props);
        this.state = {
          data: [],
          isLoaded: false,
        }
      }

      componentDidMount() {
        fetch('')
        .then(res => res.json())
        .then(json => {
          console.log(json);
          this.setState({isLoaded: true, data: json.data});
        });

      }

        render() {
        var { isLoaded, data} = this.state;
        if (!isLoaded) {
          return <div>Loading...</div>;
        }

        else{
          return (
            <div className="apiFetch">
 <ul>
                {data.map(data => (
                  <li key="{data.id}">Text:{data.text.more}</li> 
                ))}
              </ul>
            </div>
          );
        }
      }

Any help or direction would be nice. 任何帮助或指示将是很好。

Is there a particular reason you're choosing to extend the component? 您选择扩展组件是否有特定原因? For staters, the extends syntax is for JavaScript classes, but in your case you are trying to extend a function. 对于状态程序, extends语法适用于JavaScript类,但是在您的情况下,您尝试扩展函数。

If your goal is to render data received from the API, there are a few ways to achieve this. 如果您的目标是呈现从API接收的数据,则有几种方法可以实现此目的。

  1. You can make the request in a parent container component and pass the data to the child as a prop. 您可以在父容器组件中发出请求,并将数据作为道具传递给子容器。

  2. You can use a higher order component (HOC) to pass additional props to the component. 您可以使用高阶组件(HOC)将其他道具传递到该组件。 A HOC is a function that accepts a component as an argument and returns a new component. HOC是一个接受组件作为参数并返回新组件的函数。 You can read more about HOCs here: https://reactjs.org/docs/higher-order-components.html 您可以在此处阅读有关HOC的更多信息: https : //reactjs.org/docs/higher-order-components.html

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

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