[英]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我想访问 return 之外的 title 属性,以便我可以将它传递给其他人,但我不知道如何访问组件的属性这里是我的自定义组件
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.您想在他的父亲中访问子组件的
title
属性,而您声明title
值的第一刻是在子组件的渲染中。
So you got two options,所以你有两个选择,
The first is to use ref
to access the property of a child at the father.第一种是使用
ref
在父亲处访问孩子的财产。 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这种方法的优点是您仍然可以仅在渲染时声明标题,缺点是它复杂、反模式,并且 React 文档建议不要
How to call child component function from Parent in react 如何在反应中从父级调用子组件 function
The second option is to declare titles
before the render, and render a map for this array第二个选项是在渲染之前声明
titles
,并为此数组渲染 map
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现在
titels
存在于父级
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.