[英]React.js - conditionally use dangerouslySetInnerHTML
I have some code to Regex some text and wrap it in a <span />
like so: 我有一些代码到Regex的一些文本并将其包装在
<span />
如下所示:
highlightQuery() {
// will output the text response from the Model, but also highlight relevant words if they match the search query
// that the user input
let input = this.props.model.get('value');
if(!this.state.hasMatch){
return input;
}
let query = this.props.matched.query,
index = this.props.model.get('searchIndexes')[this.props.matched.index];
const replaceBetween = (str, start, end, what) => {
return str.substring(0, start) + what + str.substring(start + end);
};
let ret = replaceBetween(input, index, query.length, `<span class='highlighted'>${query}</span>`);
return ret;
},
render() {
const classes = classNames(
this.props.model.get('type'),
'character'
);
return (
<span key={this.props.model.cid} className={classes} dangerouslySetInnerHTML={ {__html: this.highlightQuery()} }>
{!this.state.hasMatch && this.highlightQuery()}
</span>
);
}
However, this yields: Uncaught Error: Invariant Violation: Can only set one of children or props.dangerouslySetInnerHTML.
但是,这会产生:
Uncaught Error: Invariant Violation: Can only set one of children or props.dangerouslySetInnerHTML.
How am I best to conditionally use dangerouslySetInnerHTML
? 我如何有条件地使用
dangerouslySetInnerHTML
?
and make sure you do not include a space between the span tags else you would run into the following error: 并确保您不在span标记之间包含空格,否则您将遇到以下错误:
invariant.js:39 Uncaught Invariant Violation: Can only set one of
children
orprops.dangerouslySetInnerHTML
.invariant.js:39 Uncaught Invariant Violation:只能设置一个
children
或props.dangerouslySetInnerHTML
。
return = <span key={this.props.model.cid} className={classes} dangerouslySetInnerHTML={ {__html: this.highlightQuery()} }>NO SPACE OR TEXT HERE</span>
You can use spread syntax if you are using ES2016. 如果您使用的是ES2016,则可以使用扩展语法。
const options = {};
if (useHTML) {
options.dangerouslySetInnerHTML = {__html: yourHTML};
} else {
options.children = [<ChildNode/>];
}
return <span {...options} className="myClassName"></span>
You can define an element (and its properties) before calling the render
function, like so: 您可以在调用
render
函数之前定义元素(及其属性),如下所示:
var return = {};
if(myCondition) {
return = <span key={this.props.model.cid} className={classes}>
{!this.state.hasMatch && this.highlightQuery()}
</span>
} else {
return = <span key={this.props.model.cid} className={classes} dangerouslySetInnerHTML={ {__html: this.highlightQuery()} }></span>
}
Then you can just render
the return
var. 然后你可以
render
return
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.