【发布时间】:2018-01-21 19:52:16
【问题描述】:
我正在尝试将以 '#' 和 '@' 开头的字符串转换为可点击的链接,为此我正在使用正则表达式来用 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>
);
}
}
【问题讨论】:
-
尝试点击而不是点击
-
还是不行。这甚至都不是在阅读 css 类。
-
onClick={()=>this.search($&)}怎么样? -
它正在打印“this.search(@nytnow)}>@nytnow”,但没有调用该函数。警告它需要在 '()' 这个括号中是 Ivalue。
-
它的印刷在哪里?按钮是否被渲染?你在页面上看到你的按钮了吗?
标签: javascript html reactjs jsx