我尝试将以'#‘和'@’开头的字符串转换为可点击的链接,为此,我使用正则表达式将该单词替换为html标签,并在其中添加onclick函数,通过调用search函数来执行操作。我在渲染部分使用了'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>
);
}
}发布于 2018-01-22 06:07:08
在我看来,您正在尝试将字符串解析为javascript代码。这通常是不可能的,而且被认为是危险的。如果您想这样做,this issue有一些见解
将按钮更改为
hit._source.text = hit._source.text.replace(re1,("“+ $& + ""));
Parser(results, { transform: () => this.htmlParserTransformer })和
import {convertNodeToElement} from "react-html-parser"
htmlParserTransform = (node, index) => {
if (node.type == "tag" && node.name == "button") { // button tag
const {id} = node.attribs // extract the actual url
return (
<button
onClick={() => this.search(id)} // click
>
{convertNodeToElement (node, index, this.htmlParserTransform)}
</span>
</a>
)
}PS:这段代码没有经过测试,但我希望我给您指出的方向是正确的。
https://stackoverflow.com/questions/48371033
复制相似问题