在Reactnative中,每当文本末尾有一个点时,我如何使文本换行



我在一个名为mainStory的数据库中的状态中包含了文本。mainStory值是从后端加载并存储在状态中的值。

mainStory = "hello mr musk. have you ever seen the movie looks completely diffrent from its add?. this is so weird."

我想在渲染时,只要末尾有一个点,就进行换行

我该怎么办?下面是我的代码。

const SecondStoryContainer = styled.View`
`;
const CardMainTxt = styled.Text`
`;
const App = () => {
const [mainStory, setMainStory] = useState('');

<SecondStoryContainer>
<CardMainTxt>
{mainStory}
</CardMainTxt>
</SecondStoryContainer>
}

这是js中的一个例子,你可以这样使用,它很管用!

const myString = 'Hello, this is a string with one line. It will soon have 2 lines.'
const stringWithNewLines = myString.replaceAll('. ', '.n');
console.log(stringWithNewLines)

您可以使用类似的东西

const newString = mainStory.replace(/./g, '.n');
console.log(newString)

好吧,我想我知道为什么replaceAll对你来说失败了。您似乎将mainStory设置为组件状态的一部分。因此,您不能通过执行mainStory=mainStory.replaceAll(…(来更改其值

你可以做一些类似的事情:

const App = () => {
const [mainStory, setMainStory] = useState('hello mr musk. have you ever seen the movie looks completely diffrent from its add?. this is so weird.');
const getContent = () => {
return mainStory.replaceAll('. ', '.n');
}
return (
<SecondStoryContainer>
<CardMainTxt>
{getContent()}
</CardMainTxt>
</SecondStoryContainer>
)
}

由于简单的换行符不会影响布局,因此需要在两个传感器之间使用<br/>标记。

// 1) Split string into array of lines. 
// You can use this syntax to split where the ". " sequence is and not remove the ". " itself.
const lines = mainStory.split(/(?<=. )/);
// 2) Add <br/> before each line and then remove 0th one. 
return (
<CardMainTxt>
{lines.flatMap((line) => [<br/>, line]).slice(1)}
</CardMainTxt>
)

或者,您可以将每一行包装成<div>

return (
<CardMainTxt>
{mainStory.split(/(?<=. )/).map((line) => (<div>{line}</div>))
</CardMainTxt>
)

React Native Edit:n实际上应该对布局有影响,所以你可以mainStory.split('. ').join('n')

最新更新