【问题标题】:How to toggle and add a styleName to a react component如何切换样式名称并将其添加到反应组件
【发布时间】:2017-01-12 19:29:31
【问题描述】:

我正在使用 @shoutem/ui 和 react-native exponent 框架创建一个 react native 应用程序。我想做一些简单的事情:如果未选中,则将 styleName 'muted' 添加到切换按钮。在这种情况下,有两个按钮 Login 和 Register 并且一个被静音,这取决于我们是否尝试使用其中一个。

我遇到语法问题,尝试在 jsx 中执行内联条件。我见过一些动态添加类对象的示例,但由于我使用的是shoutem/ui,我不确定className 是一个对象,而是一个字符串。我正在考虑只做一个内联条件来查看是否附加 styleName 字符串,但这似乎不正确。

import React, { Component } from 'react';

import {
  Image,
  Title,
  Text,
  View,
  Button,
  TextInput,
  Screen,
} from '@shoutem/ui';

export default class LoginScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isRegistering: false,
    }
  }

  toggleRegister(registering) {
    this.setState({isRegistering:registering});
  }

  render() {
    return (
      <Screen styleName="vertical collapsed paper">
        <View styleName="md-gutter">
          <View styleName="horizontal">
            <Button styleName="full-width {this.state.isRegistering ? 'muted' || ''}" onPress={()=>this.toggleRegister(false)}>
              <Text>LOGIN</Text>
            </Button>
            <Button styleName="full-width {this.state.isRegistering ? '' || 'muted'}" onPress={()=>this.toggleRegister(true)}>
              <Text>Register</Text>
            </Button>
          </View>
          <TextInput
            placeholder="Username or Email"
          />
          <TextInput
            placeholder="Password"
            secureTextEntry
          />
          <Button styleName="dark">
            <Text>Submit</Text>
          </Button>
        </View>
      </Screen>


    );
  }
}

【问题讨论】:

    标签: reactjs exponentjs


    【解决方案1】:

    我个人对 ShoutemUI 并不熟悉,但从 introduction 看来,styleName 只是 className 的替代名称(这是一个字符串,而不是一个对象,不要混淆style)。

    无论如何,您可以在一个表达式中组合多种样式,如下所示:

    <Button styleName={'full-width' + (this.state.isRegistering ? ' muted' : '')} />
    

    我还建议查看classnames util。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 2021-10-07
      • 2021-06-12
      • 2017-10-26
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      相关资源
      最近更新 更多