我正在尝试将以'#'和'@'开头的字符串转换为可点击链接,为此我正在使用html标签替换该字词并在其中添加onclick函数以执行操作调用搜索功能。我正在使用'html-react-parser'来解析渲染部分中的内容。那就是将文本转换为按钮,但是当我单击它时它没有调用search()函数。我无法理解如何解决这个问题?无论如何要解决这个或更好的方法吗?
我想要转换的数据是JSON格式,有三个不同的字段。
数据样本:
{date:"2014-06-01 04:27:08", text:"Bob Newhart, Master of the One-Sided Conversation t.co/xmdtl25WyD via @nytnow", user_id:"nytimes"}
我的代码:
import React, { Component } from 'react';
import client from './Credentials';
import '../App.css';
import Linkify from 'react-linkify';
import Parser from 'html-react-parser';
export default class Search extends Component {
constructor(props) {
super(props);
this.state = {results: []};
}
// const Autolinker = require( 'autolinker' );
search(string){
client.search({
index: 'tweet',
type: 'tweet',
size: 1000,
body: {
query: {
"bool": {
"should": [
{"match": {"text": string}},
{"match": {"user_id": string}},
{"match": {"date": string}}
]
}
},
}
}, (error, response, status) => {
if (error) {
console.log("search error: " + error)
}
else {
console.log("--- Response ---");
console.log(response);
console.log("--- Hits ---");
response.hits.hits.forEach(function (hit) {
let re1 = new RegExp("((#|@)([a-z0-9]+))", "g");
hit._source.text = hit._source.text.replace(re1, ("<button onclick={this.search($&)}>$&</button>"));
this.setState({results: this.state.results.concat([hit._source])})
}.bind(this)
);
}
// console.log(this.state.results);
})
}
handleKeyPress = (event) => {
if(event.key === 'Enter'){
event.preventDefault();
const search_query = event.target.value;
this.state.results=[];
this.search(search_query);
}
};
render() {
return(
<Linkify>
<div>
<input className={"search-bar"} type="text" onKeyPress={this.handleKeyPress.bind(this)}>
</input>
<div>{this.state.results.map((results, index) => (
<p key={index} className={"result"}><span className={"date"}>{results.date}</span> <span> </span>
<span className={"user_id"}>{results.user_id}</span> <span> </span>
<span>{Parser(results.text)}</span></p>
))}</div>
</div>
</Linkify>
);
}
}
答案 0 :(得分:0)
从我看到的,你试图将字符串解析为javascript代码。这通常是不可能的,并且被认为是危险的。如果您愿意,this issue有一些见解
将按钮更改为
hit._source.text = hit._source.text.replace(re1,(“”+ $&amp; +“”));
rustc 1.25.0-nightly (15a1e2844 2018-01-20)
和
Parser(results, { transform: () => this.htmlParserTransformer })
PS:此代码未经过测试,但我希望我能指出正确的方向。