如何将数据从NewsxWebPart.ts文件发送到Newsx.tsx文件

时间:2019-11-28 10:35:05

标签: javascript reactjs sharepoint spfx

我尝试使用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 ()}
  }
 }

1 个答案:

答案 0 :(得分:0)

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

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

上下文将从.ts传递。

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

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

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

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