简体   繁体   中英

Vue, how to pass function in props in JSX render?

My components looks like:

App.jsx

import MyInput from './MyInput';

const onChangeHandler = (val) => {
    console.log(val);
};

export default {
    render() {
        return (
            <MyInput onChange={onChangeHandler} />
        );
    },
};

and MyInput.jsx

export default {
    props: {
        onChange: {
            type: Function,
        },
    },
    render() {
        // as Sphinx suggested it should be this.$props.onChange
        return (
            <input onChange={this.$props.onChange} />
        );
    },
};

But this.onChange is undefined:

在此处输入图像描述

How to properly use this.onChange prop in MyInput component?

CodePen

Here you can find CodePen with implementation of my problem: https://codepan.net/gist/13621e2b36ca077f9be7dd899e66c056

Don't start your prop name with on. The 'on' prefix in reserved.

Credits to: nickmessing - see his answer

Check Vue API: instance property=$props , you should use _this.$props like below demo:

 Vue.config.productionTip = false Vue.component('child', { props: { onChange: { type: Function, default: function () {console.log('default')} }, }, render: function (h) { let self = this return h('input', { on: { change: function (e) { var test; (test = self.$props).onChange(e) } } }) } }) Vue.component('container1', { render: function (h) { return h('child', { props: { onChange: this.printSome } }) }, methods: { printSome: function () { console.log('container 1 custom') } } }) Vue.component('container2', { render: function (h) { return h('child', { props: { onChange: this.printSome } }) }, methods: { printSome: function () { console.log('container 2 custom') } } }) new Vue({ el: '#app' })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script> <div id="app"> <h3>Container 1</h3> <container1></container1> <h3>Container 2</h3> <container2></container2> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM