Vue,如何在JSX渲染中传递道具中的函数?

时间:2018-06-07 20:51:42

标签: javascript vue.js

我的组件如下:

App.jsx

import MyInput from './MyInput';

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

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

MyInput.jsx

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

但是this.onChange未定义:

enter image description here

如何在this.onChange组件中正确使用MyInput道具?

CodePen

在这里您可以找到CodePen并实现我的问题: https://codepan.net/gist/13621e2b36ca077f9be7dd899e66c056

2 个答案:

答案 0 :(得分:1)

请勿启用您的道具名称。保留的“on”前缀。

致记: nickmessing - see his answer

答案 1 :(得分:0)

检查Vue API: instance property=$props,您应该使用 _this.$props如下所示:

&#13;
&#13;
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'
})
&#13;
<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>
&#13;
&#13;
&#13;