繁体   English   中英

我如何将 ref 传递给 state?

[英]how do I pass ref to state?

我创建了一个 ref 并将它作为参数传递给组件。 现在我怎样才能在不派遣的情况下将它写入 State?

 const myRef = createRef<any>(); const KeyboardAvoidingWrapper: React.FC<IKeyboardAvoidingProps> = ( props: IKeyboardAvoidingProps, => { if (isAndroid) { return ( <ScrollView ref={myRef} style={styles.scroll} contentContainerStyle={styles.scrollContent}> <KeyboardAvoiding>{props.children}</KeyboardAvoiding> </ScrollView> ); }

这个例子可能对你有帮助。

<Component ref={(ref) => {
  // You can now write ref to state,
  // which I will not recommend
  // or pass it to callback
  props.getInnerRef(ref);
}} />

// You need to pass getInnerRef
<Component getInnerRef={(ref) => {
  this.innerRef = ref;
}}
const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

请参阅反应文档。 它清楚地定义了如何使用 refs。

转发引用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM