React中componentDidMount内jQuery multiselect插件回调this指向不对如何解决
问题根因
你当前遇到的this指向异常是因为afterInit使用了箭头函数:箭头函数不会创建自己的this,会继承外层作用域(也就是componentDidMount函数的this,即React类组件实例),因此multiselect插件原本对回调的this绑定逻辑会被覆盖,无法拿到预期的插件实例。
解决方案
将afterInit回调替换为普通函数即可。如果业务中需要同时访问React组件实例,可提前在外部存储组件的this引用:
class MultiSelected extends Component { componentDidMount() { this.$el = $(this.el) // 如需在回调中访问组件实例可提前存储 const componentIns = this this.$el.multiSelect({ afterInit: function() { // 此处this指向multiselect插件实例 console.log(this) // 访问组件实例用componentIns即可 }, }) } componentWillUnmount() { this.$el.multiSelect('destroy') } render() { return ( <div> <select multiple="multiple" ref={el => { this.el = el }} > <option value="1">elem 1</option> <option value="2">elem 2</option> <option value="3">elem 3</option> <option value="4">elem 4</option> </select> </div> ) } }
内容的提问来源于stack exchange,提问作者Kido
相关产品推荐
相关产品推荐

