Domanda

I have a html string embedded in a map function like this

    pnp.sp.web.lists.getByTitle("Division").items.select("Title","ID").get().then((item: any[]) =>  divtree=item.map(per =>'<li id='+per.Title+' style="cursor:pointer" onclick="myfunction()" >'+per.Title+'</li>');
    divtree.toString().replace(/,/g , "");});
    this.setState({
    divtree: divtree
  });

This is used in return like this

   <div dangerouslySetInnerHTML={{__html: this.state.divtree}} ></div>

I m declaring the function myfunction() like this

    private myfunction(): void { console.log('working') }

My problem is that when I click on the li element which was created dynamically I get the error myfunction() function is not defined

È stato utile?

Soluzione

The simplest option here is declare the function not as a class member but just like a variable in window like

window.myFunction = function {}

But I would look at removing your dangerous html insertion at all. You can return a set of React components from your .map function and insert them into div. Like that

var els = items.map(i => return (<li>...</li>););
And then
<div>{els}</div>

In that case you’ll be able to use React syntax to add even handler:

<li onClick={this.myFunction.bind(this)}>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange
scroll top