微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

createHigherOrderComponent中的useState

如何解决createHigherOrderComponent中的useState

我的反应很新,所以请不要对我坚强。

我正在尝试在HigherOrderComponent中使用useState。 不幸的是,以下代码片段给出了以下错误useState is not a function 我不知道这仅仅是useState声明的拼写,还是我在HigherOrderComponent中是否错了。

const { Fragment } = wp.element;
const { addFilter } = wp.hooks;
const { InspectorControls } = wp.editor;
const { CheckBoxControl } = wp.components;
const { createHigherOrderComponent } = wp.compose;
const { useState } = wp.element;   

const withInspectorControls = createHigherOrderComponent( ( BlockEdit ) => {
        return ( props ) => {
            //const [ isChecked,setChecked ] = useState( true ); <-- Fails here,useState is not a function
            return (
                <Fragment>
                    <BlockEdit { ...props } /> 
                    <InspectorControls>
                        <CheckBoxControl
                            heading="User"
                            label="Is author"
                            help="Is the user a author or not?"
                            checked={ isChecked } 
                            onChange={ setChecked }
                            />  
                    </InspectorControls>
                </Fragment>
    
            );
        };
    },'withInspectorControl' );
    
    addFilter( 'editor.BlockEdit','wpse',withInspectorControls );

如果有人给我小费,我将非常感激。

解决方法

我对在Wordpress中使用React并不熟悉,但是您可以尝试将此代码添加到文件顶部吗?

const {
    element: {
        useState,},} = wp;
,

我有点困惑。我将我的Wordpress核心从5.5.2更新到了5.5.3-现在我上面的代码片段也可以工作。非常感谢您的帮助。

,

你不能使用它,因为 HigherOrderComponent 返回一个 React class component 并且你不能在 Class 组件中使用 react 钩子,所以你需要遵循生命周期。在这里create createHigherOrderComponent examples您可以看到几个如何使用它的示例。

这样的东西对我有用,希望它有帮助!

     const withCoverSettingsControl = createHigherOrderComponent((BlockEdit) => {
      return class CoverExtented extends Component {
        /** @inheritdoc */
        constructor(props) {
          super(props)
          this.state = {
              newState: false
          }
          this.switchState = this.switchState.bind(this)
        }

        switchState() {
           this.setState({ newState: true })
        }

        componentDidMount() {
          console.log('init comp....')
        }
    
        render() {
          const { attributes,setAttributes } = this.props
          console.log('comp render....')
    
          return (
            <Fragment>
              <BlockEdit {...this.props} />
            </Fragment>
          )
        }
      }
    },'withCoverSettingsControl')
    
    addFilter('editor.BlockEdit','extend-core-cover',withCoverSettingsControl)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。