通过React Router的withRouter HOC转发参考

use*_*583 5 javascript reactjs react-router

我想集中精力于withRouter包装的组件。但是,当我给组件提供引用时,会收到有关将引用分配给无状态组件的警告。我假设这是因为ref被附加到withRouter HOC而不是我的组件上,因为它是有状态的。我的常规设置如下所示:

// InnerComponent.js

class InnerComponent extends Component {
   constructor(props) {
      super(props);
   }
}

export default withRouter(InnerComponent);

// App.js

class App extends Component {
   constructor(props) {
      super(props);
      this.myRef = React.createRef();
   }

render() {
    return (
       <Router>
           <InnerComponent ref={this.myRef}>
       </Router>
    );
}
Run Code Online (Sandbox Code Playgroud)

我看到这个问题以前曾被问过,但从未得到回答。我是React的新手,如果我遗漏了一些明显的东西,请原谅我。提前致谢。

编辑:我很确定我需要的是这里:https : //reacttraining.com/react-router/web/api/withRouter,在withRouter文档的wraptedComponentRef部分中,但我不知道如何实现它。

Pan*_*olo 9

根据@Ranjith Kumar 的回答,我提出了以下解决方案:

  • 更短/更简单(不需要类组件或withRef选项)
  • 在测试和开发工具中表现更好
const withRouterAndRef = Wrapped => {
  const WithRouter = withRouter(({ forwardRef, ...otherProps }) => (
    <Wrapped ref={forwardRef} {...otherProps} />
  ))
  const WithRouterAndRef = React.forwardRef((props, ref) => (
    <WithRouter {...props} forwardRef={ref} />
  ))
  const name = Wrapped.displayName || Wrapped.name
  WithRouterAndRef.displayName = `withRouterAndRef(${name})`
  return WithRouterAndRef
}
Run Code Online (Sandbox Code Playgroud)

用法是一样的:

// Before
export default withRouter(MyComponent)
// After
export default withRouterAndRef(MyComponent)
Run Code Online (Sandbox Code Playgroud)


小智 6

使用 HOC 转发内部组件引用的withRouterHOC组件

const withRouterInnerRef = (WrappedComponent) => {

    class InnerComponentWithRef extends React.Component {    
        render() {
            const { forwardRef, ...rest } = this.props;
            return <WrappedComponent {...rest} ref={forwardRef} />;
        }
    }

    const ComponentWithRef = withRouter(InnerComponentWithRef, { withRef: true });

    return React.forwardRef((props, ref) => {
        return <ComponentWithRef {...props} forwardRef={ref} />;
      });
}
Run Code Online (Sandbox Code Playgroud)

用法

class InnerComponent extends Component {
   constructor(props) {
      super(props);
   }
}

export default withRouterInnerRef(InnerComponent);
Run Code Online (Sandbox Code Playgroud)


Lau*_*ück 0

我认为你可以像这样使用React.forwardRefhttps://reactjs.org/docs/forwarding-refs.html ):

// InnerComponent.js

class InnerComponent extends Component {
   constructor(props) {
      super(props);
   }
}

export default withRouter(InnerComponent);

// App.js

const InnerComponentWithRef = React.forwardRef((props, ref) => <InnerComponent ref={ref} props={props} />);

class App extends Component {
   constructor(props) {
      super(props);
      this.myRef = React.createRef();
   }

render() {
    return (
       <Router>
           <InnerComponentWithRef ref={this.myRef}>
       </Router>
    );
}
Run Code Online (Sandbox Code Playgroud)

注意:未经测试的代码!