首页 > 专栏 > 前端 > 文章详情
React 中继承 jQuery 的 chose() 插件 发布于:2021-03-27 09:55:02   来源:React   查看:2  讨论:0
在React组件中使用jQuery原理:Hfl易塔云建站-模板下载,web开发资源,技术博客
Hfl易塔云建站-模板下载,web开发资源,技术博客
此时的 react 组件只负责渲染必要的 dom 节点。在组件的生命周期里面拿到需要的 dom 使用 jquery 插件。需要注意的是:jquery 控制的 dom 不能再让 react 操作,否则会发生冲突。Hfl易塔云建站-模板下载,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;

评论

  • 匿名