我的组件如下:
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
未定义:
如何在this.onChange
组件中正确使用MyInput
道具?
在这里您可以找到CodePen并实现我的问题: https://codepan.net/gist/13621e2b36ca077f9be7dd899e66c056
答案 0 :(得分:1)
请勿启用您的道具名称。保留的“on”前缀。
答案 1 :(得分:0)
检查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'
})
&#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;