首页 > 解决方案 > React Native:有没有办法让内联样式有状态来输出外部样式?

问题描述

如何将外部样式与具有状态的内联样式结合起来?我只想将所有样式放入样式模块中。

<View
  style={[
    styles.buttonAcceptDinamic,
    {
      backgroundColor: !this.state.micState ? null : 'rgba(255,255,255,.4)',
    },
  ]}>
  <Icon
    name={this.state.micState ? 'mic-off' : 'mic'}
    color="white"
    size={30}
  />
</View>;

React native:如何结合外部和内联样式?)这个解决方案有一个没有状态的内联样式。

编辑:代码正常工作。我只是想摆脱具有状态的内联样式,因为 VSCode 和 Error Lens(VSCode Extension) 给了我一个警告。

标签: reactjsreact-native

解决方案


一个使用钩子但实现相同目的的示例,您的语法有问题:

 <Text style={[styles.paragraph, isValid ? {'color': 'red'} : "" ]}>

世博会:https ://snack.expo.io/rLwktDEHM

import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

export default function App() {

  const [isValid, setValid] = React.useState(false);

  return (
    <View style={styles.container}>
      <Text style={[styles.paragraph, isValid ? {'color': 'red'} : "" ]}>
        Change code in the editor and watch it change on your phone! Save to get a shareable url.
      </Text>
      <TouchableOpacity onPress={() => setValid(v => !v)}>
          <Text>
            Change State
          </Text>
      </TouchableOpacity>
      <Card>
        <AssetExample />
      </Card>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

推荐阅读