我可以使用ref在外部获得连接组件的状态吗?

时间:2019-04-23 18:21:58

标签: javascript reactjs redux

我有一个显示调试控制台的记录器,如下所示:

class Logger {
    public init(props: LoggerInitProps) : void {
            (window as any).logger = this;
            this.consoleContainer = document.createElement('div');
            this.consoleContainer.classList.add('debug');
            const consoleProps = {
                ...props,
                ref: (el: any) => {
                    this.console = el;
                }
            };
            ReactDOM.render(
                React.createElement(DebugConsole, consoleProps as DebugConsoleProps),
                this.consoleContainer
            );
            document.body.appendChild(this.consoleContainer);
        }
    }
    ... other methods
}

记录器使用ref获取并控制debugConsole的状态:

    protected renderMessage(type: string, data: any): void {
        const { messages } = this.console.state;
        let newMessages = [...];
        this.console.setState({messages: [...messages, ...newMessages]});
    }

现在我需要执行一些调度,并且需要连接调试控制台,然后将其包装到具有存储的提供者:

class DebugConsole<...> {
    constructor(props){
        state={messages: [...]}
    }
    render() {
        return <div> ... some code </div>
    }
}

const DebugConsoleConnect = connect(
    (state: State) => ({data: state.data}),
    (dispatch) => ({ dispatch }) 
)(DebugConsole);

export class ProviderDebugConsole extends React.Component {
    render() {
        return(
            <Provider store={appStore}>
                <DebugConsoleConnect props={this.props}/>
            </Provider>
        )
    }
}

现在如何使用旧代码获取debugConsole的状态? 当我尝试从Providered debugConsole Property 'messages' does not exist on type 'Readonly<{}>'.

获取状态时出现错误

我已经尝试过通过带有{withRef:true}属性的ref进行传递。喜欢:

connect(
    stateToProps, 
    dispatchToProps, 
    null, 
    {withRef: true}
)(Comp)

但它仍然无法正常工作。

1 个答案:

答案 0 :(得分:0)

要解决该问题,需要传递带有{forwardRef:true}属性的ref。喜欢: 在DebugConsole

export const ConnectedDebugConsole = connect(
    stateToProps,
    dispatchToProps,
    null,
    { forwardRef: true }
)(DebugConsole);

export class DebugConsoleProvider extends React.Component<{forwardRef: any}>{
    render() {
        return(
            <Provider store={appStore}>
                <ConnectedDebugConsole ref={this.props.forwardRef}/>
            </Provider>
        )
    }
}

在记录器上

public init(props: LoggerInitProps) : void {
    if (!this.inited) {
    (window as any).logger = this;
    this.consoleContainer = document.createElement('div');
    this.consoleContainer.classList.add('debug');
    this.consoleContainer.classList.add('debug_hidden');
    const consoleProps = {
        ...props,
        forwardRef: (el: any) => {
            this.console = el;
        }
    };
    ReactDOM.render(
        React.createElement(DebugConsoleProvider, consoleProps),
        this.consoleContainer
    );
    document.body.appendChild(this.consoleContainer);

    ...
}

有效。