【问题标题】:Call redux-connected component from React using ref使用 ref 从 React 调用 redux 连接的组件
【发布时间】:2023-03-30 23:35:02
【问题描述】:

尝试使用 ref 从其父级调用组件的函数。该组件连接到 Redux。使用反应 ^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)

【问题讨论】:

    标签: reactjs redux ref


    【解决方案1】:

    this.usersTable.getWrappedInstance() 在分配 usersTable 引用之前在渲染上被热切地评估。

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

    如果使用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} />
    

    【讨论】:

      猜你喜欢
      • 2019-09-05
      • 2018-01-03
      • 1970-01-01
      • 2019-12-03
      • 2017-09-26
      • 1970-01-01
      • 2017-04-13
      • 2018-11-18
      • 1970-01-01
      相关资源
      最近更新 更多