如何在ReactJS中展示带正确间距、换行与格式的OpenAI响应?
React中正确渲染OpenAI响应格式的解决方案
问题场景
通过useState存储OpenAI API返回的响应,控制台打印时格式(换行、间距)正常,但直接渲染到页面时格式丢失。相关代码如下:
请求API代码
const [response, setResponse] = useState(); try { const res = await axios.post('https://api.openai.com/v1/completions', body, config) const completions = res.data.choices[0].text console.log(completions) setResponse(completions) setLoading(false) } catch (err) { console.error(err) setLoading(false) }
原渲染代码(格式丢失)
{loading ? ( <div className='block p-2.5 h-full w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white'>loading...</div> ) : ( <div className="block p-3 h-full w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white"> {response} </div> )}
解决方法
方法1:使用<pre>标签保留原始格式
<pre>标签会原样保留文本中的换行、空格等格式,直接替换原渲染的<div>为<pre>即可:
{loading ? ( <div className='block p-2.5 h-full w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white'>loading...</div> ) : ( <pre className="block p-3 h-full w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white"> {response} </pre> )}
方法2:通过CSS样式保留格式
如果需要更灵活的样式控制,给渲染的<div>添加whitespace-pre-wrap类(对应CSS属性white-space: pre-wrap),该属性会识别文本中的换行符并保留空格:
{loading ? ( <div className='block p-2.5 h-full w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white'>loading...</div> ) : ( <div className="block p-3 h-full w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white whitespace-pre-wrap"> {response} </div> )}
方法3:解析Markdown格式(若响应含Markdown)
如果OpenAI返回的是Markdown格式内容,可使用react-markdown库解析渲染:
- 安装依赖:
npm install react-markdown
- 使用示例:
import ReactMarkdown from 'react-markdown'; // 渲染部分 {loading ? ( <div className='block p-2.5 h-full w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white'>loading...</div> ) : ( <div className="block p-3 h-full w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white"> <ReactMarkdown>{response}</ReactMarkdown> </div> )}
内容的提问来源于stack exchange,提问作者Sujjeee
相关产品推荐
相关产品推荐

