如何在React中渲染包含可点击链接组件和换行的文本内容?
问题修复方案
错误原因
- 你错误地将React组件插入了字符串模板,JS会自动将对象类型转为字符串得到
[object Object],无法正常渲染组件。 - HTML会自动合并空白字符,模板字符串里的换行符不会被渲染为页面换行。
最优修改方案
直接修改setContent的传值,传入React节点而非字符串即可,原有渲染逻辑不需要调整:
setContent( <> hi <Typography className={classes.link} onClick={showProfile}> {him.first_name} {him.last_name} </Typography> <br /> their car is {him.car} <br /> and house is {him.house} </> )
// 渲染代码保持不变 <DialogContent>{content}</DialogContent>
特殊场景兼容方案
如果你的业务场景必须要求content为字符串格式,可以通过dangerouslySetInnerHTML配合事件委托实现,该方案存在XSS风险,非必要不推荐使用:
// 拼接带自定义标识的HTML字符串 setContent(`hi <span class="${classes.link}" data-action="showProfile"> ${him.first_name} ${him.last_name} </span> <br /> their car is ${him.car} <br /> and house is ${him.house}`) // 渲染时绑定事件 <DialogContent onClick={(e) => { if(e.target.dataset.action === 'showProfile') { showProfile() } }} dangerouslySetInnerHTML={{__html: content}} />
内容的提问来源于stack exchange,提问作者react1
相关产品推荐
相关产品推荐

