React.js - 有条件地使用dangerouslySetInnerHTML

时间:2015-08-05 14:45:14

标签: javascript reactjs react-jsx

我有一些代码用于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>
    );
}

然而,这会产生:Uncaught Error: Invariant Violation: Can only set one of children or props.dangerouslySetInnerHTML.

我最好有条件地使用dangerouslySetInnerHTML

3 个答案:

答案 0 :(得分:9)

并确保在span标记之间不包含空格,否则会遇到以下错误:

  

invariant.js:39 Uncaught Invariant Violation:只能设置其中一个   childrenprops.dangerouslySetInnerHTML

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

答案 1 :(得分:5)

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

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

答案 2 :(得分:3)

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