按钮未放置在React Native中

时间:2019-05-30 14:40:50

标签: react-native

我的按钮似乎没有放在我的本机项目中。我的代码如下所示:

<Button style = "centered"
      onPress = {() => {Alert.alert('Button tapped!');} }
      title = "Confirm"
    />

然后在样式表中,我这样做了:

 centered:{
    position: 'absolute',
    top : 350,
}

它没有用。我尝试过的其他一些事情:

style = {centered}

给出运行时错误提示找不到以变量为中心的

class = "centered"

也不做任何事情。

根据建议,我尝试为我的按钮单独创建一个单独的View,但是它给出了一个错误,指出JSX表达式必须具有一个父元素。我尝试的代码:

<View style={styles.container}>
    <Text>Select a time to be notified : </Text>
    <Picker
      style={styles.picker} itemStyle={styles.pickerItem}
      selectedValue={this.state.time}
      onValueChange={(itemValue) => this.setState({time: itemValue})}
    >
    <Picker.Item label="Now" value="now" />
      <Picker.Item label="After 1 minute" value="1min" />
      <Picker.Item label="After 5 minutes" value="5min" />
      <Picker.Item label="Custom time" value="ctime" />
    </Picker>
  </View>
  <View>
    <Button style = {{marginTop:350}}
    onPress = {() => {Alert.alert('Button tapped!');} }
    title = "Confirm"
    />
  </View>
);

样式表:

const styles = StyleSheet.create({


 container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },

  picker :{
    width: 200,
    height: 44,
    backgroundColor: '#CCE6FF',
    borderColor: 'white',
    borderWidth: 1,
  },

  pickerItem :{
    width: 200,
    height: 88,
    backgroundColor: '#CCE6FF',
    borderColor: 'black',
    borderWidth: 1,
  },

  notificationButton :{
    position: 'absolute',
    top : 50,
  },
});

3 个答案:

答案 0 :(得分:1)

您需要更改属性:

<Button style ={styles.centered}
      onPress = {() => {Alert.alert('Button tapped!');} }
      title = "Confirm"
    />

和样式:

const styles = StyleSheet.create({
  centered:{
  position: 'absolute',
  top : 350,
  }
})

答案 1 :(得分:1)

View中添加按钮,并使用alignItemsjustifyContent设置视图样式以将按钮居中。

<View>
  <View style={styles.container}>
    <Text>Select a time to be notified : </Text>
    <Picker
      style={styles.picker}
      itemStyle={styles.pickerItem}
      selectedValue={this.state.time}
      onValueChange={itemValue => this.setState({ time: itemValue })}>
      <Picker.Item label="Now" value="now" />
      <Picker.Item label="After 1 minute" value="1min" />
      <Picker.Item label="After 5 minutes" value="5min" />
      <Picker.Item label="Custom time" value="ctime" />
    </Picker>
  </View>
  <View style={styles.confirmButton}>
    <Button
      style={{ marginTop: 350 }}
      onPress={() => {
        Alert.alert('Button tapped!');
      }}
      title="Confirm"
    />
  </View>
</View>

按钮容器样式

confirmButton: {
  justifyContent: 'center',
  alignItems: 'center',
  marginTop: 10,
}

答案 2 :(得分:1)

如果您只想在屏幕上居中放置按钮,请将其包裹在Junius指定的View中。

查看您已编辑的问题,并附带代码。您只能从render方法中返回一个元素。因此,您需要将这两个View包裹在一个父View