如何使用React createElement添加点击事件

时间:2019-03-27 06:03:01

标签: javascript reactjs

以下是我用来创建HTML标签的代码。我想在此添加点击事件。如何添加呢?

let elem = React.createElement(
    this.props.tag,
    { 
        style: this.props.style,
        id: this.props.id
        onClick: ()
    },
    [this.props.text]
)

1 个答案:

答案 0 :(得分:4)

如果要创建HTML标记,只需将onClick作为函数传递给props元素。使用React.createElement可以像这样写它

let elem = React.createElement(
    this.props.tag,
    { 
        style: this.props.style,
        id: this.props.id
        onClick: () => {console.log('clicked')}
    },
    [this.props.text]
)

您还可以通过如下所示的预定义功能

let elem = React.createElement(
    this.props.tag,
    { 
        style: this.props.style,
        id: this.props.id
        onClick: this.handleClick.bind(this)
    },
    [this.props.text]
)