gpt4 book ai didi

javascript - 如何呈现句子中随机设置的粗体文本

转载 作者:行者123 更新时间:2023-11-30 13:53:49 25 4
gpt4 key购买 nike

我想在句子中的随机位置呈现粗体字符串。

到目前为止,我一直在考虑这种方法

const wordToMatch = 'apples';
const sentence = 'I like apples and bananas';

sentence.split(' ').map(string=> {
return string === wordToMatch ? <b>{string}</b> : {string}
}).join(' ');

我收到了一组对象,其中一个(我匹配的那个)看起来像这样。

$$typeof: Symbol(react.element)
key: null
props: {children: undefined}
ref: null
type: "b"
_owner: FiberNode {tag: 0, key: null, elementType: ƒ, type: ƒ, stateNode: null, …}
_store: {validated: false}

最佳答案

这应该在不加入 map 结果的情况下运行良好,只需在不匹配的单词后添加空格,React render 将渲染 map 元素(字符串或 jsx 对象)

请看下面的片段:

const wordToMatch = 'apples';
const sentence = 'I like apples and bananas';

let output = sentence.split(' ').map(string=> {
return string === wordToMatch ? <b>{string} </b> : string+" "
});

ReactDOM.render(output,document.getElementById("txt"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


<div id="txt"></div>

关于javascript - 如何呈现句子中随机设置的粗体文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57673018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com