编程语言
首页 > 编程语言> > javascript – React.js – 有条件地使用dangerouslySetInnerHTML

javascript – React.js – 有条件地使用dangerouslySetInnerHTML

作者:互联网

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

但是,这会产生:未捕获错误:不变违规:只能设置其中一个子项或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>
}

然后你可以渲染返回变量.

标签:javascript,reactjs,react-jsx
来源: https://codeday.me/bug/20190713/1446078.html