最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

block editor - Creating a Dynamic InnerBlock that updates depending on state

programmeradmin3浏览0评论

I am creating a block that will use Innerblocks to Dynamically add additional tabs depending on the number selected by the user. This number shall be passed through a Range Control.

Currently I have

 class Test extends Component {
        constructor() {
            super()
            this.state = {
                count: attributes.tabNumber
            }
            this.addTab = this.addTab.bind(this)
            this.removeTab = this.removeTab.bind(this)
        }

        addTab() {
            this.setState(prevState => {
                const updatedCount = prevState.count + 1
                setAttributes({tabNumber: updatedCount})
                return {
                    count: updatedCount
                }
            })
        }

        removeTab() {
            this.setState(prevState => {
                const updatedCount = prevState.count - 1
                setAttributes({ tabNumber: updatedCount })
                return {
                    count: updatedCount
                }
            })
        }

        render() {
            let getTabbedContent = count => {
                let templates = [];
                for (let i = 0; i < count; i++) {
                    templates.push([
                        'cs/tab'
                    ]);
                }
                return templates;
            }

            return (
                <div>
                    <h1>{this.state.count}</h1>
                    <h2>{attributes.tabNumber}</h2>
                    <button onClick={this.addTab}>Add Tab</button>
                    <button onClick={this.removeTab}>Remove Tab</button>
                    <InnerBlocks
                        allowedBlocks={ALLOWED}
                        template={getTabbedContent(attributes.tabNumber)}
                        templateLock={true}
                    />
                </div>
            )
        }
    }

The desired effect shall be when the Range Control (Or in this current case the buttons) are pressed an Inner block of cs/tab is added or removed.

Not the worlds neatest of code but currently working on creating it before shrinking it. This has also been my first full dive into the Class system of React.

addTab() and removeTab() were added for testing purposes.

发布评论

评论列表(0)

  1. 暂无评论