首页 > 解决方案 > 此代码如何将发送按钮与功能相关联,我将如何制作另一个按钮?

问题描述

两个问题:我正在研究 spfx,对于我提供的这个特定示例,我不明白发送按钮如何与 setComment() 函数关联。我创建了一个更新按钮,我想用它来更新我刚刚创建的项目。即使我已将道具传递给它,这也无济于事(可能是错误的!)

对于更新按钮,我尝试使用 React 在 JSX 中使用 onClick 传递道具,但这不起作用。我也试过在没有 $ 的情况下这样做。我创建了一组单独的函数 _readListItem() 和 _getListItem() 来帮助我,但不确定如何将它们与 _updateListItem() 结合使用,或者我是否需要它们。

import { Environment, EnvironmentType, Version } from '@microsoft/sp-core-library';
import { ISPHttpClientOptions, SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import { escape } from '@microsoft/sp-lodash-subset';
import { BaseClientSideWebPart, IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-webpart-base';
import * as strings from 'FeedbackWebpartWebPartStrings';
import styles from './FeedbackWebpart.module.scss';
import { IFeedbackWebPartProps } from './IFeedbackWebPartProps';
import {ISPListItem} from './ISPListItem';

export default class FeedbackWebpartWebPart extends BaseClientSideWebPart<IFeedbackWebPartProps> {

  public render(): void {
    this._updateListItem = this._updateListItem.bind(this);
    this._readListItem = this._readListItem.bind(this);
    this.domElement.innerHTML = `
    <div>
    <p class='${styles.titleText}'>Job Evaluation Form</p>
    <i class='ms-Icon ms-Icon--NoteForward' aria-hidden='true'></i>
    <p class='${styles.labelText}'>Name</p>
    <input type='text' class='${styles.input}' maxlength='255' placeholder='${escape(this.properties.hintText)}' />
    <br>
    <br>
    <p class='${styles.labelText}'>Job Title</p>
    <input type='text' class='${styles.input}' maxlength='255' placeholder='${escape(this.properties.hintText)}' />
    <br>
    <p class='${styles.successIndicator}'></p>
    <br>
    <br>
    <br>
    <button type='button' class='ms-Button'><span class='ms-Button-label'>Send</span></button>
    <br>
    <br>
    <button type='button' class='ms-Button' onClick='${this._updateListItem}'><span class='ms-Button-label'>Update</span></button>
    </div>`;

 //The binding below allows setComment to be used in the render and outside of it.
    this.setComment = this.setComment.bind(this);
    this._updateListItem = this._updateListItem.bind(this);
    this._readListItem = this._readListItem.bind(this);
    //Grab ALL the <input> elements
    // [0] -  just want the first element
    // cast this generic element to specific type of element (which I know that it is) as the variable is expecting a specific type
    const textInput: HTMLInputElement = this.domElement.getElementsByTagName("INPUT") [0] as HTMLInputElement;

    // setComment is used in an event listener here to be called upon whenever a user types into this input field.
    textInput.addEventListener("keyup", this.setComment);
    this.sendFeedback = this.sendFeedback.bind(this);
    const submitbutton: HTMLButtonElement = this.domElement.getElementsByTagName("BUTTON") [0] as HTMLButtonElement;

    submitbutton.onclick = this.sendFeedback;
    submitbutton.disabled = true;

  }
private _updateListItem(): void {

  const url: string = this.context.pageContext.site.absoluteUrl+"/_api/web/lists/getbytitle('Feedback')/items(1)";
  const itemDefinition : any = {
    "Title" : "Modified title field value!"};
    const headers:any = {
      "X-HTTP-Method":"MERGE",
      "IF-MATCH": "*",
    };
    const spHttpClientOptions: ISPHttpClientOptions = {
      "headers": headers,
      "body": JSON.stringify(itemDefinition)
    };
    this.context.spHttpClient.post(url, SPHttpClient.configurations.v1,spHttpClientOptions)
    .then((response: SPHttpClientResponse) => {
      if (response.status === 204) {
        this._operationResults.innerHTML = "Update: List Item updated successfully.";

      } else {
        this._operationResults.innerHTML = "Update: List Item update failed. " +response.status+" - "+response.statusText;
      }
    });
    }

private sendFeedback(): void {
  this.context.statusRenderer.clearError(this.domElement);
  const paragraphElement: HTMLParagraphElement = this.domElement.getElementsByClassName(styles.successIndicator) [0] as HTMLParagraphElement;
  paragraphElement.innerHTML="";

  if(this._commentText === undefined || this._commentText.length === 0) {
    this.context.statusRenderer.renderError(this.domElement, "Please type in a comment or a suggestion.");
    return;

  }
  if(Environment.type === EnvironmentType.Local) {
    this.context.statusRenderer.renderError(this.domElement, "Feedback can't be saved when running in local workbench");
    return;
  }

  const url: string = this.context.pageContext.site.absoluteUrl+"/_api/web/lists/getbytitle('Feedback')/items";
  const item : any = {
    "Title": this._commentText,
    "URL": window.location.href,
    "JobTitle": this._jobTitle
  };

  const spHttpClientOptions: ISPHttpClientOptions = {
    "body": JSON.stringify(item)
  };

很抱歉有很多代码,但我不知道如果我不提供它,您将如何理解我需要知道的内容。

我希望了解“发送”按钮的工作原理和“更新”按钮,以便在单击时更新任何更改的项目。

标签: reactjstypescriptsharepoint-onlinespfx

解决方案


看起来“发送”按钮 onClick 事件是使用以下代码设置的:

const submitbutton: HTMLButtonElement = this.domElement.getElementsByTagName("BUTTON") [0] as HTMLButtonElement;

submitbutton.onclick = this.sendFeedback;

这里 getElementsByTagName("BUTTON")[0] 返回在上述 HTML 中创建的第一个元素。

我想用同样的方法,更新按钮可以这样处理:

const updateButton: HTMLButtonElement = this.domElement.getElementsByTagName("BUTTON") [1] as HTMLButtonElement;

updateButton.onclick = this._updateListItem.bind(this);

注意从 [0] 到 [1] 的更改索引,以获取第二个按钮,以及 bind() 的用法。如果没有绑定,当调用 _updateListItem 时,“this”将是未定义的。


推荐阅读