简体   繁体   中英

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

I have the following spfx component which is plain javascript and works perfectly fine.

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.

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:

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:

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 . We can then implement a renderMethod for the quotes:

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.

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() {
  this.fetchData();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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