سؤال

How to call function from ".ts" file for button onClick event in tsx file?

enter image description here

this is my function in ts file:

public button_click(): void {
   alert("CLICKED!");
}

enter image description here

هل كانت مفيدة؟

المحلول

Add a property to your IAutoCompleteProps interface for your click handler. Then pass the function from the AutoCompleteWebPart into the interface as one of the component's properties.

So in your IAutoCompleteProps something like this:

export interface IAutoCompleteProps {
  //Other properties
  clickHandler: () => void;
}

Then in your AutoCompleteWebPart render:

public render(): void {
    const element: React.ReactElement<IAutoCompleteProps > = React.createElement(
      AutoComplete,
      {
        //Other props
        clickHandler: this.button_click
      }
    );

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

Then in your AutoComplete component JSX portion:

<button onClick={this.props.clickHandler}>CLICK ME</button>

نصائح أخرى

You can use the below sample which I have created using SPFx. Update the Render method and add a button with the onClick event in the React tsx file as shown below :

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

    <div className={styles.panelStyle} > 
      <br></br>

      <br></br> 
      <div className={styles.tableCaptionStyle} > Demo : Retrieve SharePoint List Items using SPFx , REST API  & React JS  </div>
      <br></br>
        <div >
        <button id="AlertMe"  type="submit" onClick={this.AlertMe} >AlertMe</button>
     </div>           
    </div>         
);  
}  
AlertMe()
{         
  alert("You have clicked Alert!");   
}

This adds the click event attribute to the button 'AlertMe'. On clicking it, the AlertMe method is called. enter image description here

Output :

enter image description here

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى sharepoint.stackexchange
scroll top