首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >onclick()在js字符串内的标记中使用时不起作用

onclick()在js字符串内的标记中使用时不起作用
EN

Stack Overflow用户
提问于 2018-01-22 03:52:17
回答 1查看 895关注 0票数 0

我尝试将以'#‘和'@’开头的字符串转换为可点击的链接,为此,我使用正则表达式将该单词替换为html标签,并在其中添加onclick函数,通过调用search函数来执行操作。我在渲染部分使用了'html-react-parser‘来解析它。这就是将文本转换为按钮,但当我单击它时,它并没有调用search()函数。我不明白我该怎么解决这个问题?有没有什么办法可以解决这个问题,或者有更好的方法?

我尝试转换的数据是JSON格式,它有三个不同的字段。

数据示例:

代码语言:javascript
复制
{date:"2014-06-01 04:27:08", text:"Bob Newhart, Master of the One-Sided Conversation t.co/xmdtl25WyD via @nytnow", user_id:"nytimes"}

我的代码:

代码语言:javascript
复制
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>&nbsp;</span>
                            <span className={"user_id"}>{results.user_id}</span> <span>&nbsp;</span>
                            <span>{Parser(results.text)}</span></p>
                    ))}</div>


                </div>
            </Linkify>

        );

    }

}
EN

回答 1

Stack Overflow用户

发布于 2018-01-22 06:07:08

在我看来,您正在尝试将字符串解析为javascript代码。这通常是不可能的,而且被认为是危险的。如果您想这样做,this issue有一些见解

将按钮更改为

hit._source.text = hit._source.text.replace(re1,("“+ $& + ""));

代码语言:javascript
复制
Parser(results, { transform: () => this.htmlParserTransformer })

代码语言:javascript
复制
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:这段代码没有经过测试,但我希望我给您指出的方向是正确的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48371033

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档