簡體   English   中英

如何在Reactjs中使用Select2?

[英]How to use Select2 with Reactjs?

我有像這樣的依賴字段

    <List>
     <select>
      <option></option>
      <option></option>
     </select>
     <select>
      <option></option>
      <option></option>
     </select>
     <input />
   </List>

如果我有5個<List/>組件。如何將Select2添加到每個組件。我在網上搜索。但找不到任何有效的解決方案。

react-select下面的代碼。獲取錯誤TypeError:event.target是未定義的

var React = require('react');
var ReactDOM = require('react-dom');
var Select = require('react-select');

var Page = React.createClass({

    getInitialState: function () {
        return {
            firstValue: ''
        }
    },

    handleFirstLevelChange : function (event) {
        this.setState({
            firstValue: event.target.value
        });
    },
    render : function(){

        var options = [
            { value: '', label: 'Select an option' },
            { value: 'one', label: 'One' },
            { value: 'two', label: 'Two' }
        ];

        return (<Select
            value={this.state.firstValue}
            options={options}
            onChange={this.handleFirstLevelChange}
            />)
    }
});

ReactDOM.render(<Page />, document.getElementById('root'));

我們正在使用這個包裝器 ,但它周圍有太多問題。

首先,由於此問題 ,您無法測試NodeJS中使用的代碼。 其次,我們通過defaultValue參數初始化各種select2組件時出現問題。 只有一個(隨機)這些元素被初始化。

因此我們將把它轉儲並盡快用react-select替換。

編輯:我們用react-select替換了react-select2-wrapper 它對我們很有用。

既然你正在使用React,你最好不要尋找React組件而不是jQuery插件。 您可以使用eaxmple react-select ,這與Select2非常相似。

如果您正在使用refs [docs] ,則可以通過componentDidMount函數中的refs屬性訪問該節點,並將其傳遞給select2()

var Select = React.createClass({
  handleChange: function () {
    this.prop.onChange(
      this.refs.myRef.value
    );
  },

  componentDidMount: function () {
    // Call select2 on your node
    var self = this;
    var node = this.refs.myRef; // or this.refs['myRef']
    $(node)
      .select2({...})
      .on('change', function() {
        // this ensures the change via select2 triggers 
        // the state change for your component 
        self.handleChange();
      });
  },

  render: function () {
    return (
      <select 
        ref="myRef"
        onChange={this.handleChange}>
        // {options}
      </select>
    );
  }
});

我不相信這是“反應方式”,但如果您不想使用react-select或其他工具,這可能會有所幫助。

如果你只是在一個react應用程序中使用jquery和select2,你只需鏈接cdn for Jquery和select2 in public / index.html里面的“head”標簽。 然后在你的src / components / component.js中。 您可以像這樣使用jquery select2:

 constructor(props) { super(props); this.state = { Provinces: [], }; this.select2PX = this.select2PX.bind(this); // this.ApiTest = this.ApiTest.bind(this); } select2PX(){ window.$(document).ready(function() { window.$('#phuong-xa').select2(); }); } componentDidMount(){ this.select2PX(); } render(){ return (.... html); } 

因為你在public / .html文件中使用cdns,所以你需要使用window。$來使用jquery。 它實現了與在html文件中使用select2相同的功能。

簡單的包裝。

在index.html上添加select2 js + css,在select輸入上寫入包裝器

function renderOptions(option_items) {
    if(option_items) {
        return Object.entries(option_items).map(function (item) {
            return <option key={item[0]} value={item[0]}>{item[1]}</option>
        })
    }
}

class Select2Input extends Component {

    constructor(props) {
        super(props)
        this.ref_input = React.createRef()
    }

    /**
    * Add select2 bind and send onChange manually
    */
    componentDidMount() {
        const self = this

        $(self.ref_input.current).select2({
            tags: true,
        }).on('change', function(event) {
            var value = $(event.currentTarget).val()
            if(self.props.multiple === true) {
                value = List(value)
            }
            self.props.onChange(self.props.name, value)
        })
    }

    /**
    * Emit change event for reload select2 if options has change
    */
    componentDidUpdate(prevProps) {
        if(prevProps.option_items !== this.props.option_items) {
            $(this.ref_input.current).change()
        }
    }

    render() {
        return <select className="form-control"
                    multiple={this.props.multiple}
                    name={this.props.name}
                    value={this.props.value}
                    disabled={this.props.disabled}
                    ref={this.ref_input}>
                            {renderOptions(this.props.option_items)}
            </select>
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM