React Native,如何删除旧样式并添加新样式

时间:2018-07-05 11:50:25

标签: javascript reactjs react-native stylesheet

我想在调用Hidden时删除View上的旧样式(InputContainer)并设置新样式(onPress)。

此来源添加了新样式,但是如何删除旧样式?

showNext = (id) => {
  this.refs["block-" + id].setNativeProps({
    style: styles.Hidden
  });
  id++;
  this.refs["block-" + id].setNativeProps({
    style: styles.InputContainer
  });
}

render() {
  return (
    <KeyboardAvoidingView style={[styles.Container]}>

      <View style={styles.InputContainer} id="block-1" ref="block-1">       
        <Text>Block 1</Text>
        <DefaultButton onPress={() => this.showNext(1)}>Ok</DefaultButton>
      </View>

      <View style={styles.Hidden} id="block-2" ref="block-2">       
        <Text>Block 2</Text>
      </View>

    </KeyboardAvoidingView>
  )
}

样式

const styles = StyleSheet.create({
  Container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  Hidden: {
    display: "none"
  },
  InputContainer: {
    width: "80%"
  }
});

1 个答案:

答案 0 :(得分:3)

我认为您可以做些简单的事情

state = {
  pressed: false
}


showNext = () => {
  this.setState({pressed: !this.state.pressed})
}

render() {
  return (
    <KeyboardAvoidingView style={[styles.Container]}>

      <View style={this.state.pressed ? styles.InputContainer : styles.Hidden} id="block-1" ref="block-1">       
        <Text>Block 1</Text>
        <DefaultButton onPress={showNext}>Ok</DefaultButton>
      </View>

      <View style={styles.Hidden} id="block-2" ref="block-2">       
        <Text>Block 2</Text>
      </View>

    </KeyboardAvoidingView>
  )
}

它也应该动态地工作:

showNext = (id) => {
  this.setState({[`blockPressed-${id}`]: !this.state[`blockPressed-${id}`]})
}

 <View style={this.state.blockPressed-1 ? stlyes.InputContainer : styles.Hidden}>       
    <Text>Block 1</Text>
    <DefaultButton onPress={() => showNext(1)}>Ok</DefaultButton>
  </View>