父高阶组件中的访问状态

时间:2018-11-08 02:23:12

标签: javascript reactjs class state higher-order-components

我正在尝试在此处开发WordPress Gutenberg块。如何重新格式化我的代码,以便能够访问以下代码段末尾定义的父高阶组件中的searchTerm状态(在类中定义)?我不想定义一个新属性,但实际上是找到一种使用已定义状态的方法。

const { __ } = wp.i18n;
const { TextControl } = wp.components;
const { withSelect } = wp.data;
const { Component, Fragment } = wp.element;

class SearchControl extends Component {

    constructor() {
        super( ...arguments );

        this.state = {
            searchTerm: null,
        };
    }

    onChangeSearchInput = ( value ) => {
        this.setState( { searchTerm: value } );
    };

    render() {

        const {
            posts,
            searchTerm,
            isRequesting,
            attributes: {
                postData,
                postType,
                searchMessage,
                showCategory,
                showAuthor,
                showImage
            },
            setAttributes,
        } = this.props;

        const { searchTerm } = this.state;

        return (

            <Fragment>
                <TextControl
                    type="search"
                    value={ searchTerm }
                    placeholder={ __( 'Type in the post title' ) }
                    onChange={ this.onChangeSearchInput }
                />
            </Fragment>
        );
    }

}

export default withSelect( ( select, state ) => {
    const { getEntityRecords } = select( 'core' );
    const { searchTerm } = state;

    return {
        posts: getEntityRecords( 'postType', 'post', { search: searchTerm, per_page: 10 } ),
    };
} )( SearchControl );

0 个答案:

没有答案