react,动态插入数据并添加事件

一段后台配置的html字段,填充到页面的dom结构。
html里面有个id,要点击事件。这样写没效果,我要怎么改

export default class Rule extends React.Component {
    constructor(props) {
        super(props);
    }


    componentDidMount(){
        const copyContentEle = document.getElementById('copy-content');
        if(!utils.isNull(copyContentEle)){
            const copyContent = copyContentEle.textContent;
            copyContentEle.click(function(){
                console.log(copyContent);
            });
        }
        
        
    }


    render() {
        const index = this.props.index;
        return (
            <div className="rule">
                {
                    this.props.data[`rule_text_${index}`] && 
                    <div>
                        <Title index={index} title={this.props.data[`rule_title_${index}`]}/>
                        <div dangerouslySetInnerHTML={{__html: this.props.data[`rule_text_${index}`]}}></div>
                    </div>
                }
            </div>
        );
    }
}
阅读 7.9k
2 个回答

以上代码会报错

Uncaught Error: Minified React error #32; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=32&args[]=130 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

图片描述

改了另外一种写法

import React from 'react';

export default class Rule extends React.Component {
    constructor(props) {
        super(props);
        
    }

    componentDidMount(){
        const ruleBox = this.refs.ruleBox;
        const index = this.props.index;
        const ruleText =  this.props.data[`rule_text_${index}`];
        ruleBox.innerHTML = ruleText;

        const copyContentEle = document.getElementById('copy-content');
        if(!utils.isNull(copyContentEle)){
            const copyContent = copyContentEle.textContent;
            copyContentEle.onclick = function(){
                //do
            }
        }
    }
    render() {
        const index = this.props.index;
        return (
            <div className="rule">
                {
                    this.props.data[`rule_text_${index}`] && 
                    <div className = "rule-content">
                        <Title index={index} title={this.props.data[`rule_title_${index}`]}/>
                        <div ref="ruleBox"></div>
                    </div>
                }
            </div>
        );
    }
}
  componentDidMount() {
    const copyContentEle = document.getElementById('copy-content');
    const copyContent = copyContentEle.textContent;
    // copyContentEle.click(function () {
    //   console.log(copyContent);
    // });
    copyContentEle.onclick=function(){
      console.log(copyContent);
    }
  }

绑定事件写错了 jq写多了吧。。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题