2

我正在尝试为我的 React Native 应用程序添加暗模式支持。我将在 mobx 商店中设置一个标志,该标志mode将是lightdark适当的。

为了将其绑定到现有应用程序中,如果可能,我想保留现有样式定义并仅在需要时覆盖(而不是将所有内容重写为明暗主题)。

我想出了一个类似下面的函数来根据当前模式返回适当的样式:

function getStyle(style) {
  let ret = [styles[style]];
  if (
    styles.hasOwnProperty(Store.mode) &&
    styles[Store.mode][style] !== "undefined"
  ) {
    ret.push(styles[Store.mode][style]);
  }
  return ret;
}

视图将呈现为:

...
<View style={getStyle("container")}>
  <Text style={getStyle("text")}>Some text</Text>
</View>
...

款式:

const styles = {
  dark: {
    container: {
      backgroundColor: "#000"
    },
    text: {
      color: "#fff"
    }
  },
  container: {
    padding: 20,
    backgroundColor: "#fff"
  },
  text: {
    fontSize: 18,
    color: "#000"
  }
};

现在这可行,但我不确定它是否会带来一些我现在不知道的性能成本(函数的使用,使用样式对象而不是StyleSheet.create......),或者我是否有更简单的方法看不到树。我也不想对每个元素都进行三元内联。

4

3 回答 3

1

我最终采取了一种稍微不同的方式,因为我会根据当前模式添加额外的样式,例如

<View style={[styles.container, theme[Store.mode].container]}>
  <Text style={[styles.text, theme[Store.mode].text]}>Some text</Text>
</View>

然后使用主题 var 覆盖

const theme = {
  light: {},
  dark: {
    container: {
      backgroundColor: "#000"
    },
    text: {
      color: "#fff"
    }
  }
};

const styles = {
  container: {
    padding: 20,
    backgroundColor: "#fff"
  },
  text: {
    fontSize: 18,
    color: "#000"
  }
};
于 2019-09-26T09:07:33.290 回答
0

我建议看一下 ReactJS 中的Context api。它为维护组件树周围的全局数据提供了一个很好的开箱即用的解决方案。

于 2019-09-18T15:10:28.573 回答
0

您可以使用React.createContext()react-native-paper

该模块使只需一个按钮即可轻松更改背景。我为你做了一个简单的例子。

我做了一个示例链接。

我做的gif

于 2019-09-18T15:25:38.363 回答