如何在基于类的组件中使用React.forwardRef?

JavaScript

凯泡芙JinJin

2020-03-12

我正在尝试使用React.forwardRef,但在如何使它在基于类的组件(而不是HOC)中工作方面遇到了麻烦。

文档示例使用元素和功能组件,甚至将类包装在函数中以用于更高阶的组件。

因此,从像这样在他们的ref.js文件:

const TextInput = React.forwardRef(
    (props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />)
);

而是将其定义如下:

class TextInput extends React.Component {
  render() {
    let { props, ref } = React.forwardRef((props, ref) => ({ props, ref }));
    return <input type="text" placeholder="Hello World" ref={ref} />;
  }
}

要么

class TextInput extends React.Component {
  render() { 
    return (
      React.forwardRef((props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />))
    );
  }
}

只能工作:/

另外,我知道我知道,裁判不是反应方式。我正在尝试使用第三方画布库,并希望将它们的一些工具添加到单独的组件中,因此我需要事件侦听器,因此需要生命周期方法。稍后可能会走不同的路线,但是我想尝试一下。

文档说这是可能的!

引用转发不限于DOM组件。您也可以将引用转发到类组件实例。

本节注释中。

但是随后他们继续使用HOC,而不仅仅是类。

第1167篇《如何在基于类的组件中使用React.forwardRef?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
StafanMandy 2020.03.12
class BeautifulInput extends React.Component {
  const { innerRef, ...props } = this.props;
  render() (
    return (
      <div style={{backgroundColor: "blue"}}>
        <input ref={innerRef} {...props} />
      </div>
    )
  )
}

const BeautifulInputForwardingRef = React.forwardRef((props, ref) => (
  <BeautifulInput {...props} innerRef={ref}/>
));

const App = () => (
  <BeautifulInputForwardingRef ref={ref => ref && ref.focus()} />
)

您需要使用其他道具名称来将引用转发到类。innerRef在许多库中常用。

小小Itachi 2020.03.12

基本上,这只是一个HOC函数。如果您想在课堂上使用它,则可以自己做,并使用常规道具。

class TextInput extends React.Component {
    render() {
        <input ref={this.props.forwardRef} />
    }
}

const ref = React.createRef();
<TextInput forwardRef={ref} />

例如,在中使用此模式,styled-components其中调用innerRef它。

蛋蛋L西里 2020.03.12

如果您需要在许多不同的组件中重复使用此功能,则可以将此功能导出为类似 withForwardingRef

const withForwardingRef = <Props extends {[_: string]: any}>(BaseComponent: React.ReactType<Props>) =>
    React.forwardRef((props, ref) => <BaseComponent {...props} forwardedRef={ref} />);

export default withForwardingRef;

用法:

const Comp = ({forwardedRef}) => (
 <input ref={forwardedRef} />
)
const EnhanceComponent = withForwardingRef<Props>(Comp);  // Now Comp has a prop called forwardedRef
MandyJinJin 2020.03.12

始终使用相同道具的想法ref可以通过使用帮助程序代理类导出来实现。

class ElemComponent extends Component {
  render() {
    return (
      <div ref={this.props.innerRef}>
        Div has ref
      </div>
    )
  }
}

export default React.forwardRef((props, ref) => <ElemComponent 
  innerRef={ref} {...props}
/>);

因此,基本上,是的,我们被迫具有其他支持转发引用的道具,但可以在中心下完成。公众将其用作常规参考非常重要。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android