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

Har*_*esh 6 javascript reactjs

以下是我用来创建 HTML 标记的代码。我想为此添加一个点击事件。我怎样才能添加这个?

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

Shu*_*tri 12

如果你正在创建一个 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]
)
Run Code Online (Sandbox Code Playgroud)

您还可以传递如下所示的预定义函数

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