关于react js:Forwardref ref为null

Fowarded ref is null

我来自这个线程:如何在基于类的组件中使用React.forwardRef?
我也非常仔细地阅读了文档,但是我的引用转发似乎根本不起作用。

要创建参考的组件:

1
2
3
4
5
6
7
8
9
10
11
12
class TextEditor extends Component {
    constructor(props: Props) {
        this.editor = createRef();
    }

    render() {
        console.log(this.editor) // -> This is always empty
        return (
            <BaseEditor ref={this.editor}/>
        );
    }
}

接收参考的组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class BaseEditor extends Component<Props> {

    render() {
        return (
            <Editor ref={this.props.innerRef}/>
        );
    }
}

const BaseEditorForwardRef = React.forwardRef((props: any, ref: any) => (
    <BaseEditor {...props} innerRef={ref} />
));

export default connect(mapStateToProps, mapDispatchToProps)(BaseEditorForwardRef)

我觉得一切都在应该的地方。如果我在不使用React.forwardRef的情况下转发引用,则ref在TextEditor中不存在。

有人知道我在做什么错吗?


您需要将ref传递给已连接Redux的组件(我没有在Redux上尝试过,但是在另一个HOC上,我希望它对您有用):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class BaseEditor extends Component<Props> {

    render() {
        return (
            <Editor ref={this.props.innerRef}/>
        );
    }
}

const Connected = connect(mapStateToProps, mapDispatchToProps)(BaseEditor)


const BaseEditorForwardRef = React.forwardRef((props: any, ref: any) => (
    <Connected {...props} innerRef={ref} />
));

export default BaseEditorForwardRef


connect将创建一个具有其自己的ref的全新组件。但是,React Redux实际上为connect提供了一个forwardRef选项,该选项应该可以转发参考。

If {forwardRef : true} has been passed to connect, adding a ref to the connected wrapper component will actually return the instance of the wrapped component.

https://react-redux.js.org/api/connect#forwardref-boolean