简体   繁体   中英

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. I want to do something simple: add a styleName 'muted' to a toggle button if it's not selected. 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. 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. 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.

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 ).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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