首页 > 解决方案 > 我如何将 ref 传递给 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>
    );
  }

标签: react-nativereduxreference

解决方案


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

<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;
}}

推荐阅读