[英]Vue, how to pass function in props in JSX render?
我的组件看起来像:
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
是未定义的:
如何在MyInput
组件中正确使用this.onChange
道具?
在这里您可以找到解决我的问题的 CodePen: https ://codepan.net/gist/13621e2b36ca077f9be7dd899e66c056
不要以 on 开头你的道具名称。 保留中的“on”前缀。
归功于: nickmessing - 见他的回答
检查Vue API: instance property=$props ,你应该使用_this.$props
像下面的演示:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.