我如何将ref传递给州?

时间:2020-11-12 08:27:04

标签: react-native redux reference

我创建了一个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>
    );
  }

2 个答案:

答案 0 :(得分:0)

此示例可能会对您有所帮助。

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

答案 1 :(得分:0)

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

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

ForwadingRefs