【问题标题】:how to get parent component background color in child component in react nativereact-native 如何在子组件中获取父组件背景颜色
【发布时间】:2020-07-12 02:55:02
【问题描述】:

我想将父组件 Card 的 backgroundColor 的值传递给子组件 CardSubTitle 并根据父 backgroundColor 更改文本颜色。 React-native 和 babel 对我来说是新的并且从未使用过状态。我尝试使用 {...props} 但没有成功。

卡片.js

const Card = (props) => {
  return (
    <TouchableItem onPress={() => {}} useOpacity>
      <View style={[styles(props).card]}>{props.children}</View>
    </TouchableItem>
  );
};

Card.propTypes = {
  onPress: T.func,
  title: T.string,
  color: T.string,
};

export default Card;

CardText.js


const Card = (props) => {
  return (
    <TouchableItem onPress={() => {}} useOpacity>
      <View style={[styles(props).card]}>{props.children}</View>
    </TouchableItem>
  );
};

Card.propTypes = {
  onPress: T.func,
  title: T.string,
  color: T.string,
};

export default Card;

【问题讨论】:

  • 我可以帮你,你能用 React hooks 吗?

标签: react-native


【解决方案1】:

您不能将props 传递给children

但你也可以

在你的 app-theme-file 中定义 Card-Background-Color 就像

myAppThemeFile.js

export const APP_CARD_COLOR = 'red';

然后在你的父组件或子组件中引用这个常量

为字幕创建一个组件,以便您可以将道具传递给

const Card = (props) => {
  return (
    <TouchableItem onPress={() => {}} useOpacity>
      <View style={[styles(props).card]}>
        <MySubtitleComponent color={props.color} value={subtitle} />  
      </View>
    </TouchableItem>
  );
};

如果您的卡的children 有点不为人知, 我建议将 card-color 添加到 global 对象并在应用中的任何位置随意引用它

const Card = (props) => {
  /**
   * Reference your card-color anywhere in your app using global.cardColor
   */
  global.cardColor = props.color; 

  return (
    <TouchableItem onPress={() => {}} useOpacity>
      <View style={[styles(props).card]}>{props.children}</View>
    </TouchableItem>
  );
};

提示:我个人不喜欢这个解决方案...最好使用redux-action来设置card-color,然后在组件中拉取那个card-color需要它

使用global 对象是一种快速简单的解决方案...不像redux-solution 可能需要更多编码...但它更健壮和安全。

【讨论】:

  • 感谢您的建议。我的卡片将接受用户的动态颜色,并且卡片内不需要有字幕。能否请您提出更多替代方案?
  • EI-Sahil 谢谢。从现在开始我将使用全局对象,并花一些时间学习 redux。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-25
  • 1970-01-01
  • 2012-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
相关资源
最近更新 更多