programing

리액션 네이티브 스타일. 폭: 백분율 - 숫자

codeshow 2023. 3. 13. 20:43
반응형

리액션 네이티브 스타일. 폭: 백분율 - 숫자

하고싶다width: 100% - 50오른쪽에 50폭의 아이콘을 추가할 수 있습니다.

나는 가지고 있다width: 100% - 20%리액션 네이티브 확장 스타일을 사용하여 작업합니다만, 할 수 있기 때문에 그것이 왜 도움이 되는지 모르겠습니다.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를 실행합니다.335console.displaces의 경우inputContainerWidth단, 폭은<autocomplete>100% 정지상태입니다.

Viktor의 의견에 동의합니다. Flex Box를 사용하여 이 작업을 수행할 수 있어야 합니다.

여기 정리한 내용이 있습니다.https://snack.expo.io/B1jDKOhyb

사용자가 설정한다.flexDirection~에 대한 형식의row, 그 다음 첫째 아이(홀더)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',
  },
});

이 문제는 치수를 사용하면 쉽게 해결할 수 있습니다.

import { Dimensions } from 'react-native';

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

export default MyComponent;

폭을 계산하지 않아도 됩니다.사용하다marginHorizontal: 50와 함께width:100또는flex:1.

당신의 코드가 작동하지 않는 이유는 그 때 렌더링되기 때문입니다.inputContainerWidth갱신되었습니다.이 작업을 수행하려면 새 렌더링을 사용해야 합니다.inputContainerWidth상태 비저장 컴포넌트는 사용할 수 없습니다.바꾸다Location표준 컴포넌트 및 추가inputContainerWidth설명하겠습니다.

사용을 검토하다useWindowDimensions부터react-native(문서 참조):

import { useWindowDimensions } from 'react-native';
const { height, width } = useWindowDimensions();

했다margin: -50그리고 그것은 나에게 효과가 있었다.

언급URL : https://stackoverflow.com/questions/43826624/react-native-styling-width-percentage-number

반응형