反应原生样式。宽度:百分比 \- 数字

新手上路,请多包涵

我想做 width: 100% - 50 所以我可以在它的右侧添加一个50宽的图标。

我有 width: 100% - 20% 使用 react-native-extended-styles 工作,但我不明白为什么这很有用,因为你可以做 width: '80%' 。我无法 width: 100% - 50 工作。有办法吗?

尝试使用 onLayout 事件来获取容器宽度,然后将容器宽度的 <autocomplete> 设置为 100% - 50 但它不起作用。

     let Location = (props) => {
      let locationInputElement

      const blur = () => {
        locationInputElement.blur()
      }

      let inputContainerWidth

      return (
        <View style={styles.formItem}>
          <View
            onLayout={(event) => {
              inputContainerWidth = event.nativeEvent.layout.width
              console.log(inputContainerWidth)
            }}

    <Autocomplete
              data={props.autocompleteResults.predictions}...
 style={{
            borderRadius: 8,
            backgroundColor: 'red',
            alignSelf: 'stretch',
            paddingLeft: 10,
            position: 'relative',
            ...styles.label,
            ...styles.labelHeight,
            width: inputContainerWidth - 50
          }}
        />
      </View>
    </View>
  )
}

它确实 console.log 335 当它 console.logs inputContainerWidth<autocomplete> 的宽度仍然是 100%。

原文由 BeniaminoBaggins 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 517
2 个回答

我同意 Viktor 的观点,你应该可以使用 Flex Box 来实现这一点。

这是我放在一起的东西: https ://snack.expo.io/B1jDKOhyb

You set the flexDirection of the formRow to row , and then the first child (the holder View for your AutoComplete component to flex: 1 .这使它填满了所有可用空间。下一个孩子 View 是您的图标持有者。您可以将其设置为您想要的任何值(在本例中为50)。

 export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.formRow}>
          <View style={styles.formItem}>
            // AutoComplete component goes here
          </View>
          <View style={styles.formIcon}>
           // Icon goes here
          </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 100
  },
  formRow: {
    flexDirection: 'row',
    height: 50,
  },
  formItem: {
    flex: 1,
    backgroundColor: 'dodgerblue',
  },
  formIcon: {
    width: 50,
    backgroundColor: 'greenyellow',
  },
});

原文由 Mike 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 Dimensions 可以很容易地解决这个问题。

 import { Dimensions } from 'react-native';

const MyComponent = () => {
  return <Text style={{height: Dimensions.get('window').height - 100}}></Text>
};

export default MyComponent;

原文由 asbmin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题