【问题标题】:onclick() is not working when using it in tag inside a js string在 js 字符串内的标签中使用 onclick() 时不起作用
【发布时间】: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>&nbsp;</span>
                            <span className={"user_id"}>{results.user_id}</span> <span>&nbsp;</span>
                            <span>{Parser(results.text)}</span></p>
                    ))}</div>


                </div>
            </Linkify>

        );

    }

}

【问题讨论】:

  • 尝试点击而不是点击
  • 还是不行。这甚至都不是在阅读 css 类。
  • onClick={()=&gt;this.search($&amp;)} 怎么样?
  • 它正在打印“this.search(@nytnow)}>@nytnow”,但没有调用该函数。警告它需要在 '()' 这个括号中是 Ivalue。
  • 它的印刷在哪里?按钮是否被渲染?你在页面上看到你的按钮了吗?

标签: javascript html reactjs jsx


【解决方案1】:

据我所知,您正在尝试将字符串解析为 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:此代码未经测试,但我希望我为您指明了正确的方向。

【讨论】:

    猜你喜欢
    • 2014-07-11
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 2022-11-18
    相关资源
    最近更新 更多