使用 ref 从 React 调用 redux-connected 组件

Call redux-connected component from React using ref

正在尝试使用 ref 从父组件调用组件的函数。该组件连接到 Redux。使用 React ^16。说:TypeError: this.usersTable.getWrappedInstance is not a function。请参阅下面的代码示例:

export default class Users extends Component {
    constructor(props){
        super(props)
        this.usersTable = React.createRef()
    }

    render() {
        return (
            <div>
                <button type="button"
                        onClick={this.usersTable.getWrappedInstance().onAddUser}>ADD NEW USER</button>

                <UsersTable onRef={node => this.usersTable = node} />
            </div>
        )
    }
}

class UsersTable extends Component {
    componentDidMount() {
        this.props.onRef(this)
    }

    onAddUser = () => {
        // DO SMTH
    }
}
export default connect(mapStateToProps, mapDispatchToProps, null, { withRef: true })(UsersTable)

this.usersTable.getWrappedInstance() 在分配 usersTable ref 之前急切地在渲染上求值。

参考混淆了。它是 React.createRef() 或自定义 onRef,而不是两者。后者不需要 getWrappedInstance() 但需要将 props 传递给具有映射函数的包装组件。

如果使用 React.createRef(),则为:

usersTable = React.createRef();

onButtonClick = () => {
  this.usersTable.current.getWrappedInstance().onAddUser();
}    

...

<button type="button" onClick={this.onButtonClick}>
  ADD NEW USER
</button>

<UsersTable ref={this.usersTable} />