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

标签 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 ()}
  }
 }

最佳答案

以将页面上下文从 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);
  }

关于javascript - 如何将数据从 NewsxWebPart.ts 文件发送到 Newsx.tsx 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59086804/

相关文章:

javascript - 我是否总是需要从 redux 中间件返回一个值?

javascript - ES2016 默认参数为空数组会导致 "no-empty-pattern"警告

sharepoint - 如何将 Word 文档作为 HTML 发布到 Sharepoint

css - 协作图表和意外样式 (SharePoint 2010)

javascript - 如何在表单提交事件后*运行一些 JavaScript?

javascript - NodeJS 中的模块导出回调用于单元测试

javascript 正则表达式无法匹配给定的字符串

javascript - 在我的应用程序登录页面上显示 git 标签(版本)

sharepoint - 如何清除 SharePoint Designer 缓存?

javascript - 使用 Google 脚本解析来自 Google Drive(而不是网页)的 HTML 文件