React.js - 有条件地使用 dangerouslySetInnerHTML

React.js - conditionally use dangerouslySetInnerHTML

我有一些代码可以对一些文本进行正则表达式并将其包装在 <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

您可以在调用 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>
}

然后你可以 render return var.

并确保您没有在 span 标签之间包含 space 否则您会 运行 出现以下错误:

invariant.js:39 Uncaught Invariant Violation: Can only set one of children or props.dangerouslySetInnerHTML.

return = <span key={this.props.model.cid} className={classes} dangerouslySetInnerHTML={ {__html: this.highlightQuery()} }>NO SPACE OR TEXT HERE</span>

如果你使用的是 ES2016,你可以使用扩展语法。

const options = {};
if (useHTML) {
  options.dangerouslySetInnerHTML = {__html: yourHTML};
} else {
  options.children = [<ChildNode/>];
}
return <span {...options} className="myClassName"></span>