在React.js中包装HTML时,避免使用dangerouslySetInnerHTML

时间:2015-08-04 09:37:03

标签: javascript reactjs react-jsx

我有此功能可突出显示组件HTML中的某些字符:

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() {
    return (
        <span dangerouslySetInnerHTML={ {__html: this.highlightQuery()} }></span>
    );
}

正如您所看到的,如果此组件的value中没有匹配项,则只返回input内容,否则将匹配的文本包装在<span />中。

我所追求的是避免使用dangerouslySetInnerHTML。这可能吗?

2 个答案:

答案 0 :(得分:0)

我不确定这会完全回答你的问题,但我会这样做以避免危险的SetInnerHTML。

UITextField

希望有所帮助

编辑:我想我理解你现在的意思,但在我看来,它会改变策略,你在渲染中工作,选择你的内容并渲染它。 (或者我仍然没有得到它...... = p)

答案 1 :(得分:0)

有没有理由highlightQuery无法返回react元素?

highlightQuery(input,query, index) {
    // will output the text response from the Model, but also highlight relevant words if they match the search query
    // that the user input
    var before = input.substring(0, index);
    var after  = input.substring(index + query.length);
    return <span>{before}<span class='highlighted'>{query}</span>{after}</span>;
},

render() {
    var input = this.props.model.get('value');
    var query = this.props.matched.query;
    var index = this.props.model.get('searchIndexes')[this.props.matched.index];

    if(!this.state.hasMatch){
        return <span>{input}</span>;
    } else {
        return highlightQuery(input, query, index);
    }

}