【React】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>

);

}

}

回答

以上代码会报错

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.

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

改了另外一种写法

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写多了吧。。

以上是 【React】react,动态插入数据并添加事件 的全部内容, 来源链接: utcz.com/a/72216.html

回到顶部