How can I insert a line break into a component in React Native?

前端 未结 24 1804
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 18:04

I want to insert a new line (like \\r\\n,
) in a Text component in React Native.

If I have:



Hi~
this
相关标签:
24条回答
  • 2020-11-28 18:37

    https://stackoverflow.com/a/44845810/10480776 @Edison D'souza's answer was exactly what I was looking for. However, it was only replacing the first occurrence of the string. Here was my solution to handling multiple <br/> tags:

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

    Sorry, I couldn't comment on his post due to the reputation score limitation.

    0 讨论(0)
  • 2020-11-28 18:39

    This worked for me

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

    (react-native 0.41.0)

    0 讨论(0)
  • 2020-11-28 18:39

    If at all you are displaying data from state variables, use this.

    <Text>{this.state.user.bio.replace('<br/>', '\n')}</Text>
    
    0 讨论(0)
  • 2020-11-28 18:40

    Another way to insert <br> between text lines that are defined in an array:

    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;
      }, []);
    

    Then the text can be used as variable:

    <Text>{textContent}</Text>
    

    If not available, Fragment can be defined this way:

    const Fragment = (props) => props.children;
    
    0 讨论(0)
  • 2020-11-28 18:41

    You can also just add it as a constant in your render method so its easy to reuse:

      render() {
        const br = `\n`;
         return (
            <Text>Capital Street{br}Cambridge{br}CB11 5XE{br}United Kingdom</Text>
         )  
      }
    
    0 讨论(0)
  • 2020-11-28 18:42

    You can use {'\n'} as line breaks. Hi~ {'\n'} this is a test message.

    0 讨论(0)
提交回复
热议问题