简体   繁体   中英

Dynamic tag name with JSX and React Native

This question is inspired by this question: Dynamic tag name in jsx and React but this time it is for React Native.

I am trying to render a <TouchableOpacity> button for iOS and <TouchableNativeFeedback> button for Android, with no success.

I tried the following code:

render() {
    const { element } = this.props;

    const ButtonElementName = Platform.OS === 'ios' ? 'TouchableOpacity' : 'TouchableNativeFeedback';

    return (
      <ButtonElementName style={styles.sectionEntryContainer}>
        <View style={styles.sectionDayContainer}>  
          <LinearGradient
            style={styles.gradientStyle}
            start={{x: 0, y: 0}} end={{x: 1, y: 0}}
            colors={COLOR_MAP[element.item.data.mood].colors}
          >
            <Text style={styles.sectionDayText}>{ moment(element.item.day, 'D').format('Do') }</Text>
          </LinearGradient>
        </View>
        <View style={styles.sectionDayDescriptionContainer}>
          <Text style={styles.sectionDayText}>{ element.item.data.optionalDescription }</Text>
        </View>
      </ButtonElementName>
    );
  }

but get the following error when trying it on the iOS Simulator:

Invariant Violation: View config not found for name TouchableOpacity

How would I go about doing this without creating a HOC?

You shouldn't reference the element by it's name, but directly by class

import {
  TouchableNativeFeedback,
  TouchableOpacity
} from 'react-native';

const Element = Platform.OS === 'ios' ? TouchableOpacity : TouchableNativeFeedback;

class SomeComponent extends React.Component {

  render() {
    const { element } = this.props;

    return (
      <Element style={styles.sectionEntryContainer}>
        <View style={styles.sectionDayContainer}>  
          <LinearGradient
            style={styles.gradientStyle}
            start={{x: 0, y: 0}} end={{x: 1, y: 0}}
            colors={COLOR_MAP[element.item.data.mood].colors}
          >
            <Text style={styles.sectionDayText}>{ moment(element.item.day, 'D').format('Do') }</Text>
          </LinearGradient>
        </View>
        <View style={styles.sectionDayDescriptionContainer}>
          <Text style={styles.sectionDayText}>{ element.item.data.optionalDescription }</Text>
        </View>
      </Element>
    );
  }
}

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