在 React 函数式组件中访问 Refs

Accessing Refs in React Functional Component

我正在使用 this 包将信用卡添加到我的应用程序,当在功能组件中使用它时,您将如何访问示例中的引用?

这是他们显示更新值的方式:

this.refs.CCInput.setValues({ number: "4242" });

我不知道如何在功能组件中访问它?

这是我编辑卡片的组件,我想将当前值添加到输入中。

import React, {useContext, useState, useRef} from 'react';
import {Text, View, StyleSheet, TouchableOpacity} from 'react-native';
import {CreditCardInput} from 'react-native-input-credit-card';

import Store from '../../store/context';

const styles = StyleSheet.create({

});

export default function EditCard(props) {
  const {navigate} = props.navigation;
  const {cardNumber} = props.navigation.state.params;
  const {state, dispatch} = useContext(Store);
  const [card, setCard] = useState(
    state.cards.find(card => {
      return card.values.number === cardNumber;
    }),
  );
  const _onChange = form => {
    if (form.valid) {
      setCard(form);
    }
  };
  const updateCard = () => {
    dispatch({
      type: 'ADD_CARD',
      payload: card,
    });
    navigate.goBack();
  };
  return (
    <View style={styles.container}>
      <CreditCardInput
        validColor={'#47B278'}
        invalidColor={'#E23C3C'}
        placeholderColor={'#efefef'}
        onChange={_onChange}
        requiresName
      />
      <TouchableOpacity
        style={
          card
            ? card.valid
              ? styles.button
              : styles.buttonDisabled
            : styles.buttonDisabled
        }
        disabled={card ? (card.valid ? false : true) : true}
        onPress={updateCard}>
        <Text style={styles.buttonText}>Update Credit Card</Text>
      </TouchableOpacity>
    </View>
  );
}

你需要使用useRef钩子:

const cciRef = useRef();

<CreditCardInput ref={cciRef}/>;
// cciRef.current holds the reference
export default function EditCard(props) {
  const cciRef = useRef();

  useEffect(() => {
    console.log(cciRef.current);
    cciRef.current.setValues({ number: "4242" });
  }, []);

  return (
    <View style={styles.container}>
      <CreditCardInput ref={cciRef} />
    </View>
  );
}