1

Here is my code sample please tell me purpose of using ref

<Camera
          ref={(cam) => {
           this.Camera = cam;
         }}
          style={styles.preview}
          aspect={camera.constants.Aspect.fill} >
          <Text style={styles.capture} 
          onPress = { this.takePicture.bind(this )}>
          [CAPTURE]
          </Text>

</Camera>
  • are you asking what are refs for? https://reactjs.org/docs/refs-and-the-dom.html – Sagiv b.g Nov 11 '17 at 10:55
  • use of ref in this specific code – user8275164 Nov 11 '17 at 10:58
  • hard to tell without the surrounding context of this code. somewhere some code is using `this.Camera` (probably) and we need to see this block of code as well to be sure what the purpose is. – Sagiv b.g Nov 11 '17 at 11:05
  • refs are generally used to access the ReactElement, just like `document.getElementById()` in normal javascript See this answer https://stackoverflow.com/questions/38093760/how-to-access-a-dom-element-in-react-what-is-the-equilvalent-of-document-getele/38093981#38093981 – Shubham Khatri Nov 11 '17 at 11:16
  • You don't have to if your are not making use of 'this.Camera' anywhere. – 10101010 Nov 11 '17 at 11:28

1 Answers1

0

You can do something like this using the reference:

    <Camera
          ref={(cam) => {
           this.Camera = cam;
         }}
          style={styles.preview}
          aspect={camera.constants.Aspect.fill} >
          <Text style={styles.capture} 
          onPress = { this.takePicture.bind(this )}>
          [CAPTURE]
          </Text>

</Camera>

takePicture() {
    this.Camera.capture()
      .then((data) => console.log(data))
      .catch(err => console.error(err));
}

ref returns a reference to the component. In the above example you are storing reference of the component Camera in this.Camera( you can name it whatever like this.xyz or whatever). Now you can access all the methods of Camera component using this.Camera. In the above example capture is a method of Camera component and you can call it like this this.Camera.capture().

You can think of it like this, for easier understanding:

Camera = { // your <Camera /> component
    capture: function(){ console.log('CAPTURE')}
}
myCamera = Camera // ref is doing something like this("myCamera" replaces "this.Camera", "Camera" replaces 'cam" )
myCamera.capture() // now you can call methods of Camera Object
Shubhnik Singh
  • 1,329
  • 10
  • 13