vue2中使用jsx,如何绑定动态事件?

render() {
    return (
        <customComponent props={{ ...props }} {...attrs}></customComponent>
    )
}

使用props={{ ...props }}可以绑定props, 使用{...attrs}可以绑定原生属性.

可是,我在attrs里添加原生事件并没有生效

const attrs = {
    onClick:() =>{}
}

使用v-on等指令, 会报错

Failed to resolve directive: on

这里的事件是不确定的,所以我无法把事件写死在标签上.
请问我该如何将动态的事件绑定在jsx的标签上

阅读 4.6k
2 个回答

在组件内部的具体标签上绑定事件,然后把handler当作props传进去绑定到标签上。


不理解为什么事件是不确定的,我觉得可以把事件逻辑放到handler里面处理

如果是按照如下的方式传递

const props = {
    onClick: () => {}
}
const attrs = {
    className: 'bar'
}
render() {
    return (
        <customComponent props={{ ...props }} {...attrs}></customComponent>
    )
}

实际的组件拿到的 props 是这样的

function customComponent(props) {
    /**
        props: {
            props: {
                onClick: () => {}
            },
            className: 'bar'
        }
    */
}

至于你在 attrs 里面加 onClick 没生效,应该是你没使用, customComponent 是你封装的组件,而事件最终是要绑定到元素上才能生效的

function customComponent(props) {
    const { onClick } = props;

    return (
        <div onClick={onClick}>click me</div>
    )
}

我看了下 vue2 的 jsx 支持不太一样
https://github.com/vuejs/jsx-...

看示例需要这样使用

<input vOn:click={onClick} />

如果想动态绑定事件这样试下

const eventProps = {
    'vOn:click': onClick
    'vOn:change': onChange
}
<input {...eventProps} />
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题