因此,目前我将尝试在我的react应用程序中显示格式化的代码,或者在本例中显示graphql操作。由状态触发,我想显示或删除某些变量。
const testing = `query {
getBooks {
${value.bookId?"id" : ""}
${value.bookEntry?"entry" : ""}
${value.bookTitle?"title" : ""}
}
}`
...
<div className="output">
<pre>
<code>{testing}</code>
</pre>
</div>
我一直在渲染这样的东西!
也许有更好的方法来解决这个问题,但值得一问!
添加一个过滤器以在渲染前删除空白。
查看下面的解决方案:
// Solution:
function clearQueryString(queryString){
const result = []
const splitted = queryString.split('n')
console.log({splitted})
for (let index = 0; index < splitted.length; index++) {
const element = splitted[index];
// regex credit: https://stackoverflow.com/questions/10261986/how-to-detect-string-which-contains-only-spaces/50971250
if (!element.replace(/s/g, '').length) {
console.log(`#${index} string only contains whitespace!`);
} else {
result.push(element)
}
}
return result.join('n')
}
// Usage:
const value = {}
const testing = `query {
getBooks {
${value.bookId?"id" : ""}
${value.bookEntry?"entry" : ""}
${value.bookTitle?"title" : ""}
author
otherfield
}
}`
document.getElementById('codeOutput').innerHTML = clearQueryString(testing);
<div className="output">
<pre>
<code id="codeOutput"></code>
</pre>
</div>