简体   繁体   English

如何切换样式名称并将其添加到React组件

[英]How to toggle and add a styleName to a react component

I'm creating a react native app using @shoutem/ui and the react-native exponent framework. 我正在使用@ shoutem / ui和react-native指数框架创建一个react native应用程序。 I want to do something simple: add a styleName 'muted' to a toggle button if it's not selected. 我想做一些简单的事情:如果未选择,将styleName'muted'添加到切换按钮。 In this case there are two buttons Login and Register and one is muted depending on whether we are trying to one or the other. 在这种情况下,有两个按钮“登录”和“注册”,其中一个被静音,这取决于我们是否尝试一个或另一个。

I'm having trouble with the syntax, trying to do the inline conditional in jsx. 我在语法上遇到麻烦,尝试在jsx中执行内联条件。 Some examples I've seen add the class object dynamically, but since I'm using shoutem/ui I'm not sure that the className is an object but rather is a string. 我已经看到了一些示例动态添加类对象,但是由于我使用的是shoutem / ui,因此我不确定className是对象而是字符串。 I was thinking of just doing an inline conditional to see whether to append the styleName string, but it doesn't seem to be correct. 我当时只是想做一个内联条件,看看是否要添加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>


    );
  }
}

I'm not personally familiar with ShoutemUI, but from the introduction it sounds to me like styleName is simply an alternative name for className (which is a string, rather than an object, not to be confused with style ). 我个人并不熟悉ShoutemUI,但是从介绍开始 ,听起来好像styleName只是className的替代名称(它是一个字符串,而不是一个对象,不要与style混淆)。

Anyhow, you could combine multiple styles in an expressions as follows: 无论如何,您可以在表达式中组合多种样式,如下所示:

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

I also suggest looking at classnames util. 我还建议查看类名 util。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM