简体   繁体   中英

how can i access the inside property (title) of an component in react native

I want to access the title property outside the return so that I can pass it to others but I don't know how to access the property of a component here is my custom component

import React, {Component} from 'react';
import { View, Text, StyleSheet } from 'react-native';
export const ClickableIcon = (props) => {
    console.warn('hi')
    return (
        <TouchableOpacity onPress={props.onPress} >
            <Text>{props.title}</Text>
        </TouchableOpacity>
    )
}

here I am using that component

import React from 'react';
import { View, Text, StyleSheet, } from 'react-native';
const Divisions = (props) => {
console.warn(title) **I want to access particular title of key 1** 
  return (
    <View style={styles.block}>

      <ClickableIcon  onPress={props.onPress} title='ac service' key='1'
       />
      <ClickableIcon onPress={props.onPress}  title='babysitter' key='2' 
       />

    </View>
  )
}
export default Divisions;

You want to access title prop of child component in his father, while the first moment you declaring the values for title is at the render of the child.

So you got two options,

The first is to use ref to access the property of a child at the father. The upside of this approach is you still can declare title only at the render, the downside is it complex, antipattern, and React docs recommend against

How to call child component function from Parent in react

The second option is to declare titles before the render, and render a map for this array


   const Divisions = (props) => {
      const titles = [ { t: 'ac service', k: 1 }, { t: 'babysitter', k: '2' } ]
      return (
        <View style={styles.block}>
         { titels.map(title => 
            <ClickableIcon onPress={props.onPress} title={title.t} key={title.k} />
          )
         }
        </View>
        )
       }

now titels are exist at parent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM