[英]useState in a createHigherOrderComponent
我对反应很陌生,所以请不要对我太强。
我正在尝试在 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 组件中使用React钩子,所以你需要遵循生命周期。 这里创建 createHigherOrderComponent 的例子你可以看到几个例子是如何使用它的。
像这样的东西对我有用,希望它有帮助!
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.