Ref无法与我构建的功能组件一起正常工作

时间:2019-10-23 11:58:08

标签: reactjs react-native

我基于react-native-24h-timepicker构建了一个简单的组件,当我尝试将ref分配给一个名为pickerRef的变量并使用该变量调用Picker函数时,我正在使用钩子,上下文API和功能组件,发生问题,根本没有调用Picker函数

当我尝试在屏幕上两次使用组件时,我单击了两个组件选择器中的任意一个,并且当我选择任何值时,即使单击第一个组件它也会影响最后一个组件,它仅影响最后呈现的组件的值。

这是代码段:

import React, { useState, useEffect } from 'react';
import { Text, View, TextInput, Dimensions, ScrollView, I18nManager } from 'react-native';
import Picker from "react-native-24h-timepicker";
import {Entypo} from '@expo/vector-icons';

//Get width of mobile screen
var width = Dimensions.get("window").width;
var height = Dimensions.get("window").height;

const TimePicker = (props) => {
    let {
        onChangeText,
        style,
        timeTextStyle,
        iconColor,
        iconSize
    } = props;
    let pickerRef = null;
    const [time, setTime] = useState('00:00');

    useEffect(() => {
        onChangeText(time);
    },
    [time])

    onCancel = () => {
        pickerRef.close();
    }

    onConfirm = (hour, minute) => {
        setTime(`${hour<10? `0`+hour : hour}:${minute}`);
        pickerRef.close();
    }

    return (
        <View>
            <View style={{...styles.textField, ...style}}>
                <Text style={{...styles.timeText, ...timeTextStyle}} onPress={() => pickerRef.open()}>{time}</Text>
                <Entypo name='select-arrows' color={iconColor} size={iconSize}/>
            </View>
            <Picker
                ref={(ref) => {
                    pickerRef = ref;
                }}
                onCancel={() => onCancel()}
                onConfirm={(hour, minute) => onConfirm(hour, minute)}
            />
        </View>
    );
}

export default TimePicker;

TimePicker.defaultProps = {
    iconColor: '#0a5ba3',
    iconSize: 15
}

const styles = {
    textField: {
        flexDirection: 'row', 
        alignSelf: 'flex-start', 
        borderRadius: 8, 
        borderWidth: 1, 
        borderColor: '#bdc3c7', 
        padding: 10
    },
    timeText: {
        fontSize: 16, 
        color: '#0a5ba3'
    }
}

Here is the screenshoot for two components

2 个答案:

答案 0 :(得分:0)

据我了解,当您复制组件时,您可能会忘记更改第二个组件的ref变量名称。

解决方案

创建单独的ref变量名称“ pickerRef1”和“ pickerRef2”,并根据需要切换状态。

答案 1 :(得分:0)

这样创建反应引用

let pickerRef = React.createRef() 

分配参考

<Picker
      ref={pickerRef }
       onCancel={() => onCancel()}
      onConfirm={(hour, minute) => onConfirm(hour, minute)}
/>

访问它

pickerRef.current.close()