在本机组件中动态创建变量

create variable dynamically in react-native component

我需要在 react-native 组件中创建一个变量,我想多次使用它...该组件的每个实例都需要有不同的变量名来引用。

<View   ref={view => { shapeView = view; }}   
        onLayout={({ nativeEvent }) => { 
            shapeView.measure( (x, y, width, height, pageX, pageY) => {
            console.log('- - - DEBUG: width:' + width + ', pageX:'+ pageX + ', pageY:' + pageY);
            let shapePickerPosition = {w: width, x: pageX, y: pageY};
            setShapeCoords(shapePickerPosition);
            })
        }}>

正如我所说,我想在一个组件中使用这段代码,并多次使用这个组件,如果我不更改 die 变量:“shapeView”,我最终只会得到最后一个实例的坐标该组件..

这是整个组件:


 import React, {useState, useEffect} from 'react';
 import {StyleSheet, View, Text, Modal, TouchableOpacity, Pressable, FlatList} from 'react-native';
 import { useTheme} from '@react-navigation/native';
 
 // ------------------PickerRow-----------------------------------------------------------------------
 function CustomPickerRow(props) {
 
   const { colors } = useTheme(); // works
   const theme = useTheme();
   const [selectedItem, setSelectedItem] = useState('choose');
   const [coordinates, setCoordinates] = useState();
 
   const setItem = (value) => {
       // set parent state
       props.action(value)
   }
 
     return (
       <View
         ref = { view => { shapeView  = view; } }
         onLayout={({ nativeEvent }) => {
             shapeView.measure( (x, y, width, height, pageX, pageY) => {
                 console.log('height:', height);
                 console.log('width:', width);
                 console.log('x:', pageX);
                 console.log('y:', pageY);
                 let coords = {w: width, x: pageX, y: pageY};
                 setCoordinates(coords);
               })
 
         }} 
         style = {{
         flexDirection: 'row', 
         justifyContent: 'space-between', 
         alignItems: 'center', 
         height: 25, 
         paddingLeft: 5, 
         marginBottom: 3, 
         backgroundColor: colors.frameBackground, 
         borderColor: colors.borderColor, 
         borderWidth: 1, 
         borderRadius: 5}}>
           <View style = {styles.icon} >
               <Text style = {styles.text}>{props.icon}</Text>
           </View>
           <View style = {styles.description} >
               <Text style = {{fontSize: 11, fontWeight: 'bold', color: colors.text, textAlign: 'left', marginLeft: 5,}}>{props.title}</Text>
           </View>
           <MyPicker data={props.data} action={setItem} position={coordinates}/>
       </View>
 
       
     );
     }
 
 
   // ------------------MyPicker-----------------------------------------------------------------------
   function MyPicker(props) {
 
     const { colors } = useTheme(); // works
     const theme = useTheme();
     const [isVisible, setIsVisible] = useState(false);
     const [selectedItem, setSelectedItem] = useState(props.data[0].key)
     const [coordinates, setCoordinates] = useState({w: 180, x: 0, y: 0});
 
     useEffect(() => {
         if (props.position) {
             setCoordinates(props.position);
         }
 
     })
   
     const setItem = item => {
       // set parent state
       props.action(item.value);
       setIsVisible(false);
       console.log("chosen value = " + item.key);
       setSelectedItem(item.key);
     }
 
     const showPicker = () => {
         setIsVisible(true);
     }
 
     const renderItem = ({item}) => {
         return <View>
                     <Pressable onPress={() => setItem(item)}>
                         <Text style={{color: colors.text, fontSize: 17, alignSelf: 'center', paddingTop: 3}}>
                             {item.key}
                         </Text>
                     </Pressable>
                 </View>
       }
 
       return (
         <View style={{flex:5, backgroundColor: 'transparent'}}>
             <TouchableOpacity onPress={showPicker}>
                 <Text style={{color: colors.textSubtitleColor, fontSize: 11, alignSelf: 'flex-end', paddingRight: 10}}>
                       {selectedItem}
                 </Text>
             </TouchableOpacity>
 
             <Modal animationType="fade"
                 transparent={true}
                 visible={isVisible}
                 style={styles.testPicker}
                 onRequestClose={() => {
                     console.log('Modal has been closed.');
                 }}
                 >
                     <View style={{  backgroundColor: colors.frameBackground,
                                     borderColor: colors.borderColor, 
                                     borderWidth: 1, 
                                     borderRadius: 5,
                                     position: 'absolute',
                                     width:  180,
                                     height: 200,
                                     left: coordinates.x, //100,
                                     top: coordinates.y //160
                                     }}>
                         <FlatList
                             data={props.data}
                             renderItem={renderItem}
                         />
                     </View>
             </Modal>
         </View>
       );
     }
 
 
     const styles = StyleSheet.create({
 
     testPicker: {
         backgroundColor: 'gray',
         position: 'absolute',
         width: 112,
         height: 200,
         left: 100,
         top: 160
       },
     icon: {
         flex: 1,
         backgroundColor: '#00529F', 
         marginRight: 0, 
         borderRadius: 5
     },
     description: {
         flex: 2,
         height: 17,
         backgroundColor: 'transparent', 
         marginRight: 0, 
         borderRadius: 5
     },
 
   });
 
   export default CustomPickerRow;

我这样称呼该组件:

<CustomPickerRow id='shapePicker' icon='2' title='Shape:' data={shapeItems} action={setShape} selectedItem={selectedShape} visible={modalVisible} />```

shapeView 应该是这样的引用:

const MyComponent = () => {
   const shapeView = useRef();

   return (
     <View
       ref={view => shapeView.current = view}
       /* could also look like this: ref={shapeView} */
       onLayout={({nativeEvent}) => {
          shapeView.current.measure(...);
       }
     />
   )
}

不应该是这样的:

let shapeView; // this is outside your component - it shouldn't be here
const MyComponent = () => {

   return (
     <View
       ref={view => shapeView = view}
       onLayout={({nativeEvent}) => {
          shapeView.measure(...);
       }
     />
   )
}

在基于 class 的组件中,它可能如下所示:


class MyComponent extends React.Component {

    constructor() {
       this.shapeView = React.createRef();
    }

    render() {
       return (
         <View
           ref={this.shapeView}
           onLayout={({nativeEvent}) => {
              this.shapeView.current.measure(...);
           }
         />
       )
    }
}