将 React 与 Sharepoint Online 结合使用第 1 部分

Using React with Sharepoint Online Part 1

我正在观看 Pluralsight course
在工作中,我将 React 与 Sharepoint Online 结合使用。我有一个呈现组件(例如标签、文本框、人物选择器)的页面,但没有命令 document.getElementbyID。 Sharepoint 在线工作方式是否与 Pluralsight 课程操场不同 jscomplete.com 这是我的代码。我已经删除了公司的敏感信息。 该代码有效。我只是想了解为什么我不必使用 document.getElementbyID.

```
import * as React from 'react';
import styles from './FinanceAccReq.module.scss';
import { IFinanceAccReqProps } from './IFinanceAccReqProps';
import { IFinanceAccReqState } from './IFinanceAccReqState';
import {IComboBoxTogglesExampleState}from './IComboBoxTogglesExampleState';

// @pnp/sp imports  
import { sp } from '@pnp/sp';  
import { PeoplePicker, PrincipalType } from "@pnp/spfx-controls-react/lib/PeoplePicker";
import { getGUID } from "@pnp/common";

import { DefaultButton } from 'office-ui-fabric-react/lib/Button'; 
import { autobind } from 'office-ui-fabric-react'; 
import { Label } from 'office-ui-fabric-react/lib/Label';
import { TextField,MaskedTextField  } from 'office-ui-fabric-react/lib/TextField';

import { Toggle } from 'office-ui-fabric-react/lib/Toggle';
import { Stack, IStackTokens } from 'office-ui-fabric-react/lib/Stack';
import { getId } from 'office-ui-fabric-react/lib/Utilities';
import { WebPartContext } from '@microsoft/sp-webpart-base';
import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown';

import { bool } from 'prop-types';
//import { IOfficeFabricProps } from '../IOfficeFabricProps';
import { DetailsList, DetailsListLayoutMode, Selection, IColumn } from 'office-ui-fabric- 
  react/lib/DetailsList';
import { MarqueeSelection } from 'office-ui-fabric-react/lib/MarqueeSelection';
import { ComboBox, Fabric, IComboBoxOption, mergeStyles,IComboBoxProps, 
SelectableOptionMenuItemType,PrimaryButton} from 'office-ui-fabric-react/lib/index';
import {SPData} from './SPData';
import { TagPicker, IBasePicker, ITag } from 'office-ui-fabric-react/lib/Pickers';
import { Checkbox } from 'office-ui-fabric-react/lib/Checkbox';

const rootClass = mergeStyles({
  maxWidth: 500
});

export default class financeAccReq extends React.Component<IFinanceAccReqProps, 
IFinanceAccReqState,IComboBoxTogglesExampleState> {  
private INITIAL_OPTIONS: ITag[] = [];
private _picker = React.createRef<IBasePicker<ITag>>();
constructor(props: IFinanceAccReqProps, state: IFinanceAccReqState) {
super(props);
//super();
this.handleFirstName = this.handleFirstName.bind(this);
this.handleSurName = this.handleSurName.bind(this);

this.handleWindowsID = this.handleWindowsID.bind(this);
this.handleEmail = this.handleEmail.bind(this);
this.handleCostCentreCode=this.handleCostCentreCode.bind(this);
this.handleTeamName=this.handleTeamName.bind(this);
//this._onCheckboxChange = this._onCheckboxChange.bind(this);
this._system1=this._system1.bind(this);
this.system2=this._system2.bind(this);


this.state = {
  addUsers: [],
  firstName: "",
  surName: "",
  windowsID:"",
  costCentreCode:"",
  email:"",
  teamName:"",
  titleError:"",
  firstNameError: "",
  surNameError: "",
  windowsIDError:"",
  costCentreCodeError:"",
  lineManagerError:"",
  emailError:"",
  selectedItems: [],
  dpselectedItem: undefined,
  dpselectedCostCentre:undefined,
  dpisystem1:undefined,
  dpisystem2:false,
  costCentreList:[],
  INITIAL_OPTIONS: [],
  confirmationMessage: ""
 };

}




public componentDidMount(){ 

this.INITIAL_OPTIONS = [];
sp.web.lists.getByTitle("CostCentres").items.getAll().then((result: any)=>{
  for(let i: number = 0; i< result.length; i++) {
    const b: SPData = result[i];
    //const c: IComboBoxOption={key:b.Column1, text: b.CostCentreInfo};
    const c: ITag={key:b.Column1, name: b.CostCentreInfo};
    this.INITIAL_OPTIONS.push(c);
}

});
}

public render(): React.ReactElement<IFinanceAccReqProps> 

{
//const { dpselectedItem, dpselectedItems } = this.state;
const { dpselectedItem } = this.state;
const { dpselectedCostCentre} = this.state;
//const { dynamicErrorValue} = this.state;
const { System1Approver } = this.state;
const stackTokens: IStackTokens = { childrenGap: 1 };
const { system1,system2} = this.state;
const { firstName, surName } = this.state;
const maskFormat: { [key: string]: RegExp } = {'*': /[0-9]/};



   const wrapperClassName = mergeStyles({
    display: 'flex',
    selectors: {
    '& > *': { marginRight: '20px' },
    '& .ms-ComboBox': { maxWidth: '300px' }
    }
    });



return (
  <div className={ styles.financeAccReq }>
    <div className={ styles.container }>
      <div className={ styles.row }>
        <div className={ styles.column }>
          {/* <span className={ styles.title }>Welcome to SharePoint!</span> */}
          <p className={ styles.subTitle }>This form should be completed by the new user’s line manager.  You will be e-mailed to confirm the user has been set up as requested.</p>
          <p className={ styles.subTitle }>If you have any questions regarding this form please contact your Finance Business Partner.</p>
          <p className={ styles.subTitle }>It can take up to 5 working days to complete the setup process, failure to complete mandatory fields may result in a further delay.</p>
          <div className="ms-Grid-col ms-u-m4 block">
          {/* <div className="errorMessage">
              <TextField defaultValue=""  errorMessage={this.state.confirmationMessage} />
           </div> */}

            <label className="ms-Label">Title</label>
          </div>
          <div className="ms-Grid-col ms-u-m8 block">

            <Dropdown
              //placeHolder="Select an Option"
              //label="Title"
              id="component"
              selectedKey={dpselectedItem ? dpselectedItem.key : undefined}
              //ariaLabel="Title"
              options={[
                { key: 'Please select', text: 'Please select' },
                { key: 'Mr', text: 'Mr' },
                { key: 'Mrs', text: 'Mrs' },
                { key: 'Ms', text: 'Ms' },
                { key: 'Dr', text: 'Dr' }
              ]}
              errorMessage={this.state.titleError}
              onChanged={this._changeTitleState}
              onFocus={this._log('onFocus called')}
              onBlur={this._log('onBlur called')}
            />
            </div>
          <div className="ms-Grid-col ms-u-m4 block">
            <label className="ms-Label">First Name *</label>
          </div>
          <div className="ms-Grid-col ms-u-m8 block">
            <TextField value={this.state.firstName}  onChanged={this.handleFirstName} errorMessage={this.state.firstNameError}/>
          </div>
          <div className="ms-Grid-col ms-u-m4 block">
            <label className="ms-Label">Surname *</label>
          </div>
          <div className="ms-Grid-col ms-u-m8 block">
            <TextField value={this.state.surName} onChanged={this.handleSurName} errorMessage={this.state.surNameError}/>
          </div>

           <div className="ms-Grid-col ms-u-m4 block">
              <label className="ms-Label">Windows id is the user id you use to log on to your PC/Laptop e.g. smitha</label>
              <p></p>
              <label className="ms-Label">Windows ID * </label>
           </div>
           <div className="ms-Grid-col ms-u-lg block">
              <TextField value={this.state.windowsID} onChanged={this.handleWindowsID}  errorMessage={this.state.windowsIDError} />

           </div>
           <div className="ms-Grid-col ms-u-m4 block">
              <label className="ms-Label">Cost Centre Code *</label>
           </div>


           <div className="ms-Grid-col ms-u-m4 block">               
           <TagPicker
          componentRef={this._picker}
      onResolveSuggestions={this._onFilterChangedNoFilter}
      onItemSelected={this._onItemSelected}
      getTextFromItem={this._getTextFromItem}
      pickerSuggestionsProps={{
        suggestionsHeaderText: 'Suggested Tags',
        noResultsFoundText: 'No Color Tags Found'
      }}
      itemLimit={1}
      disabled={false}
      inputProps={{
        onBlur: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onBlur called'),
        onFocus: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onFocus called'),
        'aria-label': 'Tag Picker'
      }}
    />

      </div>




           <div className="ms-Grid-col ms-u-m4 block">
              <label className="ms-Label">Email *</label>
           </div>
           <div className="errorMessage">
              <TextField defaultValue="@xxx.org.uk" value={this.state.email} onChanged={this.handleEmail}  errorMessage={this.state.emailError} />
           </div>
          <div className="ms-Grid-col ms-u-m4 block">
            <label className="ms-Label">Line Manager *</label><br />
          </div>

            <PeoplePicker
            context={this.props.context}
            titleText=""
            personSelectionLimit={1}
            groupName={""} // Leave this blank in case you want to filter from all users
            showtooltip={true}
            isRequired={true}
            disabled={false}
            ensureUser={true}
            selectedItems={this._getPeoplePickerItems}
            showHiddenInUI={false}
            principalTypes={[PrincipalType.User,PrincipalType.SharePointGroup]}
            errorMessageClassName="ms-Grid-col ms-u-m8 block"
            errorMessage={this.state.lineManagerError}
            resolveDelay={1000} /> 


           <div className="ms-Grid-col ms-u-m4 block">
              <label className="ms-Label">Team Name (for users of ...)</label>
           </div>
           <div className="errorMessage">
              <TextField  value={this.state.teamName} onChanged={this.handleTeamName}   />
           </div>
            <Stack tokens={stackTokens}>
                <Toggle  inlineLabel onText="Access Required" offText=" Access Not Required"  onChange= {this._changeSystem1UserState} />
                <Toggle  inlineLabel onText="Approval Required" offText="Approval Not Required"  onChange= {this._changeSystem2ApproverState} />
            </Stack>



            <DefaultButton 
              color="blue"
              className="button"
              data-automation-id="addSelectedUsers"  
              title="Submit"//Add Selected User"  
              onClick={this.addSelectedUsers}>  

              Submit 
            </DefaultButton>  

        </div>
      </div>
    </div>
  </div>
);
}


```

在您的代码中,我们不需要使用 document.getElementById 来获取 DOM 元素。

如果你想使用它,我们可以在 React SPFx web 部件的 componentDidMount() 方法中添加一些代码。

示例

public render(): React.ReactElement<IFinanceAccReqProps> {    
    return (
        <div className={ styles.financeAccReq }>
            <div className={ styles.container }>
                <div className={ styles.row }>
                    <input type="button" className={styles.button} value="Mytest" id="btnSubmit"/>
                </div>
            </div>
        </div>
    );
}
public componentDidMount(){
    let btnTest=document.getElementById("btnSubmit") as HTMLInputElement;
    alert(btnTest.value);
}

更多关于 SPFx web 部件的示例解决方案供您参考。

SharePoint Framework Client-Side Web Part Samples & Tutorial Materials