我有一些代码可以对一些文本进行正则表达式并将其包装在 <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>
);
}
但是,这会产生:Uncaught Error: Invariant Violation: Can only set one of children or props.dangerouslySetInnerHTML.
我如何最好地有条件地使用 dangerouslySetInnerHTML
?
最佳答案
并确保您没有在 span 标签之间包含空格,否则您会遇到以下错误:
invariant.js:39 Uncaught Invariant Violation: Can only set one of
children
orprops.dangerouslySetInnerHTML
.
return = <span key={this.props.model.cid} className={classes} dangerouslySetInnerHTML={ {__html: this.highlightQuery()} }>NO SPACE OR TEXT HERE</span>
关于javascript - React.js - 有条件地使用 dangerouslySetInnerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31835778/