I'm following the second tutorial from the SharePoint Framework dev center:

Connect to SharePoint

It states that you can retrieve details from this.context.pageContext, however this is no longer the case with the GA (1.0.0) release as the codebase has changed, and the documentation and tutorials haven't been updated to reflect this. The documentation seems to point to either IWebPartContext, or PageContext, but I'm just a little lost on how exactly to retrieve the page context from the component (webparts\helloWorld\components\HelloWorld.tsx).

Could someone shed some light on the new method for going about this?

有帮助吗?

解决方案

this.context.pageContext is available on render() method within top level class that extends BaseClientSideWebPart. Simply pass this.context as a props of to HelloWorld.tsx to reuse it.

Sample (HelloWorldWebpart.ts):

public render(): void {
const element: React.ReactElement<any > = React.createElement(
   HelloWorld,
   {
     description: this.properties.description,
     context: this.context
   }
);

 ReactDom.render(element, this.domElement);
}

And in HelloWorld.tsx you should be able to retrieve the context as this.props.context

Or alternatively use react redux to store the context on initialization onInit() method (https://dev.office.com/sharepoint/reference/spfx/sp-webpart-base/oninit-baseclientsidewebpart)

其他提示

It is better to use correct type WebPartContext instead of any. Don't forget to put namespace.

import { WebPartContext } from '@microsoft/sp-webpart-base';

export interface WebPartProps {
   context: WebPartContext;
   description: string;
}
...

public render(): void {
   const element: React.ReactElement<WebPartProps> = React.createElement(
   HelloWorld,
   {
     description: this.properties.description,
     context: this.context
   }
);

 ReactDom.render(element, this.domElement);
}

Here is more info WebPartContext class

Here is an example of passing pageContext to React component:

Add property to component interface. Note that I import PageContent declaration for nice IntelliSence pop-ups (I use VS Code)

    import { PageContext } from '@microsoft/sp-page-context'; // load page context declaration
    export interface IHelloWorldProps {
      description: string;
      pageContext: PageContext;// here we passing page context
    }

Then I pass pageContect from Render method of SPFx web part:

      public render(): void {
        const element: React.ReactElement<IHelloWorldProps> = React.createElement(
          HelloWorld,
          {
            description: this.properties.description,
            pageContext: this.context.pageContext
          }
        );

        ReactDom.render(element, this.domElement);
      }

And part of code from the React component itself:

    <p>Loading from {escape(this.props.pageContext.web.title)}</p>
许可以下: CC-BY-SA归因
scroll top