React.createRef不起作用-无法为函数组件提供引用

问题描述

我有这个父类组件

class TransferHolder extends Component {

    constructor(props) {
        super(props);
        this.transfer = React.createRef();
    }

    render() {
        return (
            <div>
                <h1>HELLO !</h1>
                <Transfer ref={this.transfer}/>
                <Button onClick={() => {
                    const TransferRef = this.transfer.current;
                    console.log('Selected: ',TransferRef.state.projectForm.users.right)
                }}>
                    Print
                </Button>
            </div>

        )
    }

}

const mapStatetoProps = state => {
    return {
        
    };
};

const mapdispatchToProps = dispatch => {
    return {
        
    };
};

export default connect(mapStatetoProps,mapdispatchToProps)(TransferHolder);

当我访问页面时,会自动显示一个错误提示

index.js:1 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `TransferHolder`.
    in ConnectFunction (at TransferHolder.js:19)
    in div (at TransferHolder.js:17)
    in TransferHolder (created by ConnectFunction)
    in ConnectFunction (created by Context.Consumer)
    in Content (at ContentRoute.js:23)

我只想访问<Transfer>组件的状态,该组件是基于类的组件。但是它也包装在redux connect()中,所以我不知道是否能将其转换为功能性的。

解决方法

假设您的组件Transfer的代码如下:

const Transfer = props => <p {...props}>Some Transfer component</p>;

如果您像上面那样使用此组件

<Transfer ref={this.transfer} />

它将失败,并显示错误消息

警告:不能为功能组件提供引用。尝试访问此引用将失败。您是要使用React.forwardRef()吗?

因为默认情况下普通功能组件无法处理引用。为了避免该错误,您必须将组件包装在forwardRef中:

const Transfer = forwardRef((props,ref) => <p {...props} ref={ref}>Some Transfer component</p>;