简体   繁体   中英

Why is my child container taking full width when the parent has a padding on it in my react-native app?

The Problem

I have a simple react native app using styled-components with it.

I have a simple Container that has flex: 1 and a padding: 10px

I also got a child button that has these props: width: 100%; flex-basis: 25% width: 100%; flex-basis: 25%

So my expectation is it should take the full width of it's parent container and then subtracts the 10px on all sides. But it does not. The children takes up the full width of the device as you can see in this screenshot here:

在此处输入图片说明

As you can see the orange box is the children but it takes the full width. And I don't get why?

Here is the code snippet (only parts that may cause the problem, SafeAreaView comes from react-navigation and makes sure that the status bar is free):

const Container = styled.SafeAreaView`
  flex: 1;
  background-color: papayawhip;
  align-items: center;
  padding: 10px;
`;

const NewGame = styled.TouchableOpacity`
  background: palevioletred;
  flex-basis: 25%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
`;

const Home = () => {
  console.log("hihihoho");
  return (
    <Container>
      <NewGame>
        <NewGameTitle>Neues Spiel</NewGameTitle>
      </NewGame>
      <Title>Up and running!</Title>
    </Container>
  );
};

So at this point I debugged the app and toggled the inspector and can clearly see the padding but the child still takes up the whole width.

Do you guys know why?

Edit: I added in another Container with a styled.View and set yet another flex: 1 and padding: 10px . Now this workaround seems to work. I think it has something to do with react-navigation's SafeAreaView

Try giving padding to the child component. Also you can try giving dynamic width to the button like Dimension.get(window).width - 20 and style as alignSelf:'center' .

This might work

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