2017-05-07 53 views
0

我想要做width: 100% - 50,所以我可以在右邊添加一個寬度爲50的圖標。反應原生樣式。 width:percent - number

我有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%還是。

+1

爲什麼不使用flexbox? –

+0

@ViktorSeč就我所知,Flexbox沒有辦法從全寬拿走50個像素。 – BeniaminoBaggins

回答

2

我同意Viktor,你應該能夠使用Flex Box來實現這一點。

這裏的東西我放在一起:https://snack.expo.io/B1jDKOhyb

您可以設置formRow的flexDirectionrow,然後將第一個孩子(持有者View爲您自動完成組件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', 
    }, 
}); 
+0

很乾淨。看起來像我想要的,在博覽會上觀看演示:)當我回家並標記爲答案時,嘗試它。謝謝! – BeniaminoBaggins

1

你可以不用計算寬度。使用marginHorizontal: 50width:100flex:1

你的代碼不工作,因爲它被呈現,然後inputContainerWidth更新。爲了使它工作,應該有另一個新的渲染inputContainerWidth。所以你不能使用無狀態的組件。將Location更改爲常規組件,並將inputContainerWidth添加到狀態。

+0

謝謝,這是有道理的。 – BeniaminoBaggins

0

我想你可以簡單地做這個來計算您的寬度

寬度:'calc(100% - 50px)'