admin管理员组文章数量:1122846
I have a Context.Provider with a value setup in slider/edit.js
.
When I import it in the child component slide/edit.js
with useContext
it returns undefined
I don't see what I'm missing here
For context here is the folder structure
src
slider
edit.js
index.js
slide
edit.js
index.js
build
slider
index.js
slide
index.js
index.js
import { registerBlockType } from '@wordpress/blocks';
import './style.scss';
/**
* Internal dependencies
*/
import Edit from './edit';
import save from './save';
import metadata from './block.json';
/**
* Every block starts by registering a new block type definition.
*
* @see /
*/
registerBlockType( metadata.name, {
/**
* @see ./edit.js
*/
edit: Edit,
/**
* @see ./save.js
*/
save,
} );
slider/edit.js
import React, { createContext, useRef } from 'react'
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor'
export const SlideContext = createContext()
export default function Edit() {
const slideRefs = useRef([])
const setSlideRef = (ref, index) => {
slideRefs.current[index] = ref
console.log('setSlideRef called with ref:', ref, 'and index:', index)
}
// some code omitted for brevity
console.log('Rendering Slider component with context value:', { setSlideRef })
const blockProps = useBlockProps()
return (
<SlideContext.Provider value={{ setSlideRef }}>
<div {...blockProps}>
<div className='splash-slider__wrapper'>
<div
className='splash-slider__track'
>
<InnerBlocks
allowedBlocks={['splash-blocks/slide']}
renderAppender={() => <InnerBlocks.ButtonBlockAppender />}
templateLock={false}
/>
</div>
</div>
</div>
</SlideContext.Provider>
)
}
slide/edit.js
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor'
import { useEffect, useRef, useContext } from '@wordpress/element' // Same as React
import { SlideContext } from '../slider/edit' // Import the context from the parent block
export default function Edit({ attributes, setAttributes, clientId }) {
const blockProps = useBlockProps({
className: 'splash-slider__slide'
})
const slideRef = useRef()
const slideContext = useContext(SlideContext)
console.log('slideContext:', slideContext) // logs: undefined
const { setSlideRef } = slideContext || {}
useEffect(() => {
console.log('slideRef.current:', slideRef.current) // logs correctly
if (setSlideRef && slideRef.current) {
console.log('Setting slideRef with clientId:', clientId)
setSlideRef(slideRef, clientId)
}
}, [setSlideRef, clientId])
return (
<div {...blockProps} ref={slideRef}>
// InspectorControls and PanelBody omitted for brevity
<InnerBlocks />
</div>
)
}
本文标签: block editorGutenberg DevReact ContextProvider returns undefined
版权声明:本文标题:block editor - Gutenberg Dev - React Context.Provider returns undefined 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736299731a1930562.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论