简体   繁体   中英

When using React CommandBar in SPFx project, how can build items[] array in separate file including setting parent component state?

I'm new to React/Typescript/SPFx and I am using the React CommandBar component in my SPFx webpart. The CommandBar needs the commands defined in an array called farItems[]. The items array has the properties of each command including one that is the onClick method. In my case, the onClick method is passed down to my CommandBar.tsx file through it's props.

I can build the "farItems" array in the same tsx file as the CommandBar component including the onClick method from the parent class. But I want to move the "building farItems array" process to a separate file to make it more reusable.

I summarized the current code state in this gist

toggleTips is the function I have on the main react component (PivotTiles.tsx) to change the state. I'm passing the function down to CommandBar.tsx through it's props and so if I build the items array in that file, all is well. But i want to be able to import the farItems[] from another file.

I am hoping to be able to build the farItems[] array in another file so it's more reusable.

With my current state of the code, I do have everything working in a separate file as long as I only try adding something like console.log() in the onClick. My hurdle is passing down the function from the parent to change the state and getting the syntax/logic correct.

Thanks

Thanks to some help from @AndrewConnell I was able to pass in the callback function. See the gist for his suggestion and the couple small things I had to tweak to get it working:

Forked Gist from Andrew with my comments attached at the end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM