【问题标题】:How to send data from NewsxWebPart.ts file to Newsx.tsx file如何将数据从 NewsxWebPart.ts 文件发送到 Newsx.tsx 文件
【发布时间】:2020-03-23 23:45:08
【问题描述】:

我曾尝试使用 this.properties,但我在 Newsx.tsx 文件中获得了未定义的值。我能够在 News.tsx 文件中获得 this.props.description,但不是 this.props.data。我在 OnInit() 中设置数据,这是一个异步方法

下面是我的 NewsxWebpart.ts 文件

import * as React from 'react';
import * as ReactDom from 'react-dom';

export interface INewsxWebPartProps {
  description: string;
  data:any;

  }

var newst = new Array ;
export default class NewsxWebPart extends BaseClientSideWebPart<INewsxWebPartProps> 
{
    public async onInit(): Promise<void> 
    {
       /* ajax calls to get data */
       /* getting the data inside the variable "newst"*/
       this.properties.data = newst
    }
    public render(){
      /* rendering*/ }
}

这是我的 News.tsx 文件

import * as React from 'react';
import styles from './Newsx.module.scss';
import { INewsxProps } from './INewsxProps';

export default class Newsx extends React.Component<INewsxProps, {}> { 

constructor(props:any){
 super(props);
 }
componentDidMount(){
 console.log("Hello "+this.props.description);
  console.log("Hello "+ this.props.data);

}
 public render(): React.ReactElement<INewsxProps> {
  return ()}
  }
 }

【问题讨论】:

    标签: javascript reactjs sharepoint spfx


    【解决方案1】:

    以将页面上下文从 webpart 传递到组件为例(这将经常使用)。

    在组件属性界面,添加需要从webpart(.ts)获取的属性。

    上下文将从 .ts 传递。

    import { WebPartContext } from '@microsoft/sp-webpart-base';
    export interface IPnpReactProps {
      description: string;
      context: WebPartContext;
    }
    

    在 webpart(.ts) 文件中,上下文将传递给组件(.tsx)。

    public render(): void {
        const element: React.ReactElement<IPnpReactProps > = React.createElement(
          PnpReact,
          {
            description: this.properties.description,
            context:this.context
          }
        );
    
        ReactDom.render(element, this.domElement);
      }
    

    【讨论】:

    • 感谢您的回答,但问题是我从 asyc 调用中获得了价值。 "context:this.context" this 在我得到值之前首先被调用。我试过 setTimeout 但没有工作。在此方法之前有一个异步 oninit() 方法,我从中获取上下文值。
    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    相关资源
    最近更新 更多