如何使用React-Redux> = v6.0访问ref?

 收藏

in React-Redux >= v6.0 connnect() options support a new parameter, forwardRef: boolean.

如果已传递{forwardRef:true}进行连接,则向连接的包装器组件添加ref实际上将返回被包装组件的实例。

因此,在名为“ WithFields”的HoC中,我写:

 [...]
 import Form from '.../components/form';

   const WithFields = (WrappedComponent) => connect(mapStateToProps, {someMethod}, null, {forwardRef: true})(class extends React.Component {
 [...]

   render(
        return(<WrappedComponent ref={ref => this.wrappedComponent = ref }/>)
    )
}

   [...]

   let Customer = WithFields(fields, 'customers', 'Dati cliente')(Card);
    export default Customer;

现在,在Ticket组件中,我将使用一种方法来获取Customer ref,但是如何?

     import Customer from '....';

      class Ticket extends Component {

           SOME_METHOD_TO_GET_THE_REF_OF_THE_HOC_COMPONENT() {
                  ?????????
             }

           render() {
               [....]

               <Customer/> 
            }
   }
回复
  • 花朵朵 回复

    You should get the ref method as props for the Ticket component assuming this is the returned component from the HOC.

    So in your Ticket component you can use it like this this.props.ref. You can also check in react dev tools if it is showing as the props for the Ticket component