简体   繁体   English

如何将纯JavaScript重写为React组件(foreach)

[英]how to rewrite plain javascript into a react component (foreach)

I have the following spfx component which is plain javascript and works perfectly fine. 我有以下spfx组件,它是纯JavaScript,工作正常。

import { Version } from '@microsoft/sp-core-library';
import {
  BaseClientSideWebPart,
  IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';

import styles from './MyQuotesWebPart.module.scss';
import * as strings from 'MyQuotesWebPartStrings';

import { IQuotes, IQuote } from './QuoteContracts';
import { IDataReader, DataReaderFactory } from './DataReader';

export interface IMyQuotesWebPartProps {
  description: string;
}

export default class MyQuotesWebPart extends BaseClientSideWebPart<IMyQuotesWebPartProps> {

  constructor() {
    super();
    this._dataReader = DataReaderFactory.getReader(this.context);
  }

  private _dataReader : IDataReader;

  public render(): void {
    this.domElement.innerHTML = `
      <div class="${styles.myQuotes}">
        <div class="${styles.container}">
          <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
            <div class="ms-Grid-col ms-lg10 ms-xl8 ms-xlPush2 ms-lgPush1">
              <span class="ms-font-xl ms-fontColor-white">Famous Quotes</span>
              <div class="ms-font-l ms-fontColor-white" id="quotesContainer"></div>
            </div>
          </div>
        </div>
      </div>`;

      this.renderData();
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }

  private renderData(): void {
    this._dataReader.getData().then((response) => {
      this.renderQuotes(response.Quotes);
    });
  }

  private renderQuotes(items: IQuote[]): void {
    let html: string = '';
    items.forEach((item: IQuote) => {
      html += `
        <div>${escape(item.Quote)}</div>
        <div class="${styles.author}">${escape(item.Author)}</div>  
      `;
    });

    const listContainer: Element = this.domElement.querySelector('#quotesContainer');
    listContainer.innerHTML = html;
  }
}

And I am trying to create a react component, but I am not sure how to use the render data and how to use a foreach in the resultset received to render it, basically the question is how can Integrate it into the render method. 我正在尝试创建一个react组件,但是我不确定如何使用渲染数据以及如何在接收到的结果集中使用foreach进行渲染,基本上的问题是如何将其集成到render方法中。

import * as React from 'react';
import styles from './Solid.module.scss';
import { ISolidProps } from './ISolidProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { IQuotes, IQuote } from './QuoteContracts';
import { IDataReader, DataReaderFactory } from './DataReader';


export default class Solid extends React.Component<ISolidProps, {}> {

  constructor() {
    super();
    this._dataReader = DataReaderFactory.getReader(this.context);
  }

  private _dataReader : IDataReader;

  public render(): React.ReactElement<ISolidProps> {
    return (
      <div className={ styles.solid }>
        <div className={ styles.container }>
          <div className={ styles.row }>
            <div className={ styles.column }>
              <span className={ styles.title }>Welcome to SharePoint!</span>
              <p className={ styles.subTitle }>Customize SharePoint experiences using Web Parts.</p>
              <p className={ styles.description }>{escape(this.props.description)}</p>
              <a href="https://aka.ms/spfx" className={ styles.button }>
                <span className={ styles.label }>Learn more</span>
              </a>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

Update 1: 更新1:

I have my interfaces like this: 我有这样的界面:

export interface IQuotes {
    Quotes: IQuote[];
}

export interface IQuote {
    Author: string;
    Quote: string;
}

Since the request to get the data will be asynchronous, you should make this into a member function on your React component like so: 由于获取数据的请求将是异步的,因此您应该将其放入React组件的成员函数中,如下所示:

fetchData = () => {
  this._dataReader.getData().then((response) => {
    this.setState({
      quotes: response.Quotes,
    });
  });
 }

This will trigger a render when the method is called unless you prevent an update in shouldComponentUpdate . 除非您阻止shouldComponentUpdate的更新,否则将在调用该方法时触发渲染。 We can then implement a renderMethod for the quotes: 然后,我们可以为引号实现renderMethod:

renderQuotes = () => this.state.quotes.map(quote => (
  <React.Fragment>
    <div>${escape(quote.Quote)}</div>
    <div class="${styles.author}">${escape(quote.Author)}</div>  
  </React.Fragment>
);

You don't have to use a Fragment as it's a part of React 16.3, it's just useful here. 您不必使用Fragment因为它是React 16.3的一部分,在这里很有用。

Your primary render method can then render 然后,您的主要渲染方法可以渲染

<div>
  {this.renderQuotes()}
</div>

and in componentDidMount which is when you can make network requests etc. You can call fetchData . 以及在componentDidMount ,这是您可以发出网络请求等的时间。您可以调用fetchData

componentDidMount() {
  this.fetchData();
}

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

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