itsource

React Native의 컴포넌트에 줄 바꿈을 삽입하려면 어떻게 해야 합니까?

mycopycode 2022. 11. 5. 17:28
반응형

React Native의 컴포넌트에 줄 바꿈을 삽입하려면 어떻게 해야 합니까?

React Native의 Text 컴포넌트에 새로운 행(\r\n, <br/> 등)을 삽입합니다.

있는 경우:

<text>
<br />
Hi~<br />
this is a test message.<br />
</text>

[ ]는 [Respect Native]를 렌더링합니다.Hi~ this is a test message.

다음과 같이 새 줄을 추가할 수 있는 렌더 텍스트가 있습니까?

Hi~
this is a test message.

이것으로 충분합니다.

<Text>
Hi~{"\n"}
this is a test message.
</Text>

다음 작업도 가능합니다.

<Text>{`
Hi~
this is a test message.
`}</Text>

끈 안에 물건을 넣을 필요가 없기 때문에 쉽게 할 수 있다고 생각합니다.한 번 감으면 줄 바꿈이 모두 유지됩니다.

용도:

<Text>{`Hi,\nCurtis!`}</Text>

결과:

안녕하세요.

커티스!

해결책 1:

<Text>
Hi~{"\n"}
this is a test message.
</Text>

해결책 2:

 <Text>{`
  line 1
  line 2
 `}</Text>

해결책 3:

가지 .<br/> 삭제:

<Text style={{ whiteSpace: "pre-line" }}>
    {"Hi<br/> this is a test message.".split("<br/>").join("\n")}
</Text>

해결책 4:

maxWidth line

<Text style={{ maxWidth:200}}>this is a test message. this is a test message</Text>

이건 내게 효과가 있었다.

<Text>{`Hi~\nthis is a test message.`}</Text>

(102 ~ 0.41.0)

상태 변수에서 데이터를 표시할 경우 이를 사용합니다.

<Text>{this.state.user.bio.replace('<br/>', '\n')}</Text>

하시면 됩니다.{'\n'} {'\입니다.{'\n'} {'\n'

https://stackoverflow.com/a/44845810/10480776 @Edison D'souza의 답변은 바로 제가 찾던 답변이었습니다.다만, 이것은 문자열의 첫 번째 항목을 대체했을 뿐입니다.여기 여러 가지 문제를 해결하기 위한 솔루션이 있습니다.<br/> 삭제:

<Typography style={{ whiteSpace: "pre-line" }}>
    {shortDescription.split("<br/>").join("\n")}
</Typography>

죄송합니다, 평판 점수 제한 때문에 그의 게시물에 댓글을 달 수 없었습니다.

편집:

템플릿 리터럴을 사용하는 경우(내 참조)<Text> 줄 할 수도

import React, { Component } from 'react';
import { Text, View } from "react-native";

export default class extends Component {

 (...)

 render(){
  return (
    <View>
      <Text>{`
        1. line 1
        2. line 2
        3. line 3
      `}</Text>
    </View>
  );
 }
}

코드를 잘 들여쓰기 위해 3진 연산자로 분기하는 한 줄의 솔루션이 필요했습니다.

{foo ? `First line of text\nSecond line of text` : `Single line of text`}

서브슬림 구문을 강조 표시하면 줄 바꿈 문자를 강조 표시할 수 있습니다.

숭고한 구문 강조

이렇게 사용해보시면 됩니다.

<text>{`${val}\n`}</text>

이것은 좋은 질문입니다, 당신은 이것을 여러 가지 방법으로 할 수 있습니다. 먼저

<View>
    <Text>
        Hi this is first line  {\n}  hi this is second line 
    </Text>
</View>

즉, 백슬래시 n을 사용하여 선을 깰 수 있습니다.

둘째

<View>
     <Text>
         Hi this is first line
     </Text>
     <View>
         <Text>
             hi this is second line 
         </Text>
     </View>
</View>

즉, 첫 번째 <View> 안에 있는 다른 <View> 컴포넌트를 사용하여 <Text> 컴포넌트에 랩할 수 있습니다.

해피 코딩

렌더 메서드에 상수로 추가하여 쉽게 재사용할 수도 있습니다.

  render() {
    const br = `\n`;
     return (
        <Text>Capital Street{br}Cambridge{br}CB11 5XE{br}United Kingdom</Text>
     )  
  }

다음과 같이 사용할 수 있습니다.

<Text>{`Hi~
this is a test message.`}</Text>

다음과 같이 할 수 있습니다.

{'작성\n계정'}

★★★★★★★★★★★★★★★★★★★★★★★{'\n'}

<Text>

   Hello {'\n'}

   World!

</Text>

가장 깨끗하고 유연한 방법 중 하나는 템플릿 리터럴을 사용하는 것입니다.

이 기능을 사용하면 텍스트 본문에 문자열 변수의 내용을 표시할 때 보다 깔끔하고 쉽게 표시할 수 있다는 장점이 있습니다.

(백틱 문자의 사용법에 주의해 주세요.

const customMessage = 'This is a test message';
<Text>
{`
  Hi~
  ${customMessage}
`}
</Text>

결과적으로

Hi~
This is a test message

다음은 TypeScript를 사용한 React(원어민 대응이 아님)용 솔루션입니다.

React Native에도 동일한 개념을 적용할 수 있습니다.

import React from 'react';

type Props = {
  children: string;
  Wrapper?: any;
}

/**
 * Automatically break lines for text
 *
 * Avoids relying on <br /> for every line break
 *
 * @example
 * <Text>
 *   {`
 *     First line
 *
 *     Another line, which will respect line break
 *  `}
 * </Text>
 * @param props
 */
export const Text: React.FunctionComponent<Props> = (props) => {
  const { children, Wrapper = 'div' } = props;

  return (
    <Wrapper style={{ whiteSpace: 'pre-line' }}>
      {children}
    </Wrapper>
  );
};

export default Text;

사용방법:

<Text>
  {`
    This page uses server side rendering (SSR)

    Each page refresh (either SSR or CSR) queries the GraphQL API and displays products below:
  `}
</Text>

디스플레이:

사용하기 쉬운 백틱(ES 6 기능)

솔루션 1

const Message = 'This is a message';

<Text>
{`
  Hi~
  ${Message}
`}
</Text>

솔루션 2 텍스트에 "\n"을 추가합니다.

<Text>
Hi~{"\n"}
This is a message.
</Text>

다음을 수행합니다.

<Text>

 { "Hi~ \n this is a test message." }

<Text/>

데이터를 취득하는 경우state variable or propsText 컴포넌트에는 minWidth, maxWidth의 스타일프롭이 있습니다

const {height,width} = Dimensions.get('screen');

const string = `This is the description coming from the state variable, It may long thank this` 

<Text style={{ maxWidth:width/2}}>{string}</Text>

화면 너비의 50%가 텍스트로 표시됩니다.

여기에는 두 가지 주요 해결책이 있습니다.

방법 1: 다음 명령어를 추가합니다.'\n'아래와 같이

<Text>
   First Line {'\n'} Second Line.
</Text>

방법 2: 다음과 같이 문자열 리터럴에 줄 바꿈을 추가합니다.

 <Text>
   `First Line  
   Second Line`.
 </Text>

상세한 것에 대하여는, 다음의 튜토리얼을 참조해 주세요.

https://sourcefreeze.com/how-to-insert-a-line-break-into-a-text-component-in-react-native/

줄을 끊고 싶은 곳에 {"\n"}을(를) 사용하십시오.

삽입하는 다른 방법<br>배열에 정의된 텍스트 행 간:

import react, { Fragment } from 'react';

const lines = [
  'One line',
  'Another line',
];

const textContent =
  lines.reduce(items, line, index) => {
    if (index > 0) {
      items.push(<br key={'br-'+index}/>);
    }
    items.push(<Fragment key={'item-'+index}>{line}</Fragment>);
    return items;
  }, []);

그런 다음 텍스트를 변수로 사용할 수 있습니다.

<Text>{textContent}</Text>

사용할 수 없는 경우Fragment는 다음과 같이 정의할 수 있습니다.

const Fragment = (props) => props.children;

이 코드는 내 환경에서 작동합니다.(194~180.63.4)

const charChangeLine = `
`
// const charChangeLine = "\n" // or it is ok

const textWithChangeLine = "abc\ndef"

<Text>{textWithChangeLine.replace('¥n', charChangeLine)}</Text>

결과

abc
def

꽤 오래된 것은 알지만, 통상의 방법으로 텍스트를 전달할 수 있는 자동 줄 바꿈 솔루션을 생각해 냈습니다(꼼수 없음).

다음 컴포넌트를 만들었습니다.

import React, {} from "react";
import {Text} from "react-native";

function MultiLineText({children,  ...otherProps}) {

const splits = children.split("\\n")
console.log(splits);
const items = []
for (let s of splits){
  items.push(s)
  items.push("\n")
}

  return (
    <Text {...otherProps}>{items}</Text>
  );
}


export default MultiLineText;

그럼 이렇게 쓰시면 되겠네요.

<MultiLineText style={styles.text}>This is the first line\nThis is teh second line</MultiLineText>

어레이의 각 문자열에 대해 새로운 행을 할당하는 솔루션을 찾고 있는 경우 다음과 같은 작업을 수행할 수 있습니다.

import * as React from 'react';
import { Text, View} from 'react-native';


export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      description: ['Line 1', 'Line 2', 'Line 3'],
    };
  }

  render() {
    // Separate each string with a new line
    let description = this.state.description.join('\n\n');

    let descriptionElement = (
      <Text>{description}</Text>
    );

    return (
      <View style={{marginTop: 50}}>
        {descriptionElement}
      </View>
    );
  }
}

라이브의 예에 대해서는, 스낵을 참조해 주세요.https://snack.expo.io/ @cmacdonacha / snap - new - break - line - snap

가끔 이렇게 씁니다.

<Text>
  You have {" "}
  {remaining}$ {" "}
  from{" "}
  {total}$
<Text>

(내게는 더 선명해 보이니까)

UL이나 OL과 같은 리스트를 사용하고 make list style none과 같은 스타일링을 하면 사용할 수 있습니다.<li> dhdhdhhd </li>

사용하다\n텍스트와 css로white-space: pre-wrap;

언급URL : https://stackoverflow.com/questions/32469570/how-can-i-insert-a-line-break-into-a-text-component-in-react-native

반응형