在React组件中使用jQuery原理:
KxL易塔云建站-模板下载,web开发资源,技术博客KxL易塔云建站-模板下载,web开发资源,技术博客此时的 react 组件只负责渲染必要的 dom 节点。在组件的生命周期里面拿到需要的 dom 使用 jquery 插件。需要注意的是:jquery 控制的 dom 不能再让 react 操作,否则会发生冲突。KxL易塔云建站-模板下载,web开发资源,技术博客
完成版演示:(基于jQuery中的chose插件)
function Example() {
return (
<Chosen onChange={value => console.log(value)}>
<option>vanilla</option>
<option>chocolate</option>
<option>strawberry</option>
</Chosen>
);
}
class Chosen extends React.Component {
componentDidMount() {
this.$el = $(this.el);
this.$el.chosen();
this.handleChange = this.handleChange.bind(this);
this.$el.on('change', this.handleChange);
}
componentDidUpdate(prevProps) {
if (prevProps.children !== this.props.children) {
this.$el.trigger("chosen:updated");
}
}
componentWillUnmount() {
this.$el.off('change', this.handleChange);
this.$el.chosen('destroy');
}
handleChange(e) {
this.props.onChange(e.target.value);
}
render() {
return (
<div>
<select className="Chosen-select" ref={el => this.el = el}>
{this.props.children}
</select>
</div>
);
}
}
export default Chosen;