简体   繁体   English

如何使用 react-bootstrap 创建动态下拉列表

[英]How do I create a dynamic drop down list with react-bootstrap

The example code in the react-bootstrap site shows the following. react-bootstrap 站点中的示例代码显示如下。 I need to drive the options using an array, but I'm having trouble finding examples that will compile.我需要使用数组来驱动选项,但我无法找到可以编译的示例。

<Input type="select" label="Multiple Select" multiple>
  <option value="select">select (multiple)</option>
  <option value="other">...</option>
</Input>

You can start with these two functions.您可以从这两个功能开始。 The first will create your select options dynamically based on the props passed to the page.第一个将根据传递给页面的道具动态创建您的选择选项。 If they are mapped to the state then the select will recreate itself.如果它们被映射到状态,那么选择将重新创建自己。

 createSelectItems() {
     let items = [];         
     for (let i = 0; i <= this.props.maxValue; i++) {             
          items.push(<option key={i} value={i}>{i}</option>);   
          //here I will be creating my options dynamically based on
          //what props are currently passed to the parent component
     }
     return items;
 }  

onDropdownSelected(e) {
    console.log("THE VAL", e.target.value);
    //here you will see the current selected value of the select input
}

Then you will have this block of code inside render.然后你将在渲染中拥有这段代码。 You will pass a function reference to the onChange prop and everytime onChange is called the selected object will bind with that function automatically.您将传递一个对 onChange 道具的函数引用,每次调用 onChange 时,所选对象将自动与该函数绑定。 And instead of manually writing your options you will just call the createSelectItems() function which will build and return your options based on some constraints (which can change).而不是手动编写您的选项,您只需调用 createSelectItems() 函数,该函数将根据某些约束(可以更改)构建并返回您的选项。

  <Input type="select" onChange={this.onDropdownSelected} label="Multiple Select" multiple>
       {this.createSelectItems()}
  </Input>

My working example我的工作示例

this.countryData = [
    { value: 'USA', name: 'USA' },
    { value: 'CANADA', name: 'CANADA' }            
];

<select name="country" value={this.state.data.country}>
    {this.countryData.map((e, key) => {
        return <option key={key} value={e.value}>{e.name}</option>;
    })}
</select>

bind dynamic drop using arrow function.使用箭头函数绑定动态放置。

 class BindDropDown extends React.Component { constructor(props) { super(props); this.state = { values: [ { name: 'One', id: 1 }, { name: 'Two', id: 2 }, { name: 'Three', id: 3 }, { name: 'four', id: 4 } ] }; } render() { let optionTemplate = this.state.values.map(v => ( <option value={v.id}>{v.name}</option> )); return ( <label> Pick your favorite Number: <select value={this.state.value} onChange={this.handleChange}> {optionTemplate} </select> </label> ); } } ReactDOM.render( <BindDropDown />, document.getElementById('root') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"> <!-- This element's contents will be replaced with your component. --> </div>

// on component load, load this list of values
// or we can get this details from api call also    
const animalsList = [
{
    id: 1,
    value: 'Tiger'
}, {
    id: 2,
    value: 'Lion'
}, {
    id: 3,
    value: 'Dog'
}, {
    id: 4,
    value: 'Cat'
}
];

// generage select dropdown option list dynamically
function Options({ options }) {
    return (
        options.map(option => 
                    <option key={option.id} value={option.value}>                                   
                    {option.value}
                    </option>)
                   );
}

<select
name="animal"
className="form-control">
<Options options={animalsList} />
</select>

A 1 liner would be: 1 班轮将是:

import * as YourTypes from 'Constants/YourTypes';
....
<Input ...>
    {Object.keys(YourTypes).map((t,i) => <option key={i} value={t}>{t}</option>)}
</Input>

Assuming you store the list constants in a separate file (and you should, unless they're downloaded from a web service):假设您将列表常量存储在一个单独的文件中(您应该这样做,除非它们是从 Web 服务下载的):

# YourTypes.js
export const MY_TYPE_1="My Type 1"
....

你需要为映射添加键,否则它会抛出警告,因为每个道具都应该有一个唯一的键。代码修改如下: let optionTemplate = this.state.values.map((v, index) => ({v.name})) ;

Basically all you need to do, is to map array.基本上你需要做的就是映射数组。 This will return a list of <option> elements, which you can place inside form to render.这将返回一个<option>元素列表,您可以将其放置在表单中进行渲染。

array.map((element, index) => <option key={index}>{element}</option>)

Complete function component, that renders <option> s from array saved in component's state.完整的函数组件,从保存在组件状态中的数组中渲染<option> s。 Multiple property let's you CTRL-click many elements to select. Multiple属性让您按住 CTRL 键并单击多个元素以进行选择。 Remove it, if you want dropdown menu.删除它,如果你想要下拉菜单。

import React, { useState } from "react";

const ExampleComponent = () => {
    const [options, setOptions] = useState(["option 1", "option 2", "option 3"]);

    return (
        <form>
            <select multiple>
            { options.map((element, index) => <option key={index}>{element}</option>) }
            </select>
            <button>Add</button>
        </form>
    );
}

component with multiple select多选组件

Working example: https://codesandbox.io/s/blue-moon-rt6k6?file=/src/App.js工作示例: https : //codesandbox.io/s/blue-moon-rt6k6?file=/src/App.js

You can create dynamic select options by map()您可以通过 map() 创建动态选择选项

Example code示例代码

return (
    <select className="form-control"
            value={this.state.value}
            onChange={event => this.setState({selectedMsgTemplate: event.target.value})}>
        {
            templates.map(msgTemplate => {
                return (
                    <option key={msgTemplate.id} value={msgTemplate.text}>
                        Select one...
                    </option>
                )
            })
        }
    </select>
)
  </label>
);

I was able to do this using Typeahead .我能够使用Typeahead做到这一点。 It looks bit lengthy for a simple scenario but I'm posting this as it will be helpful for someone.对于一个简单的场景,它看起来有点冗长,但我发布这个是因为它对某人有帮助。

First I have created a component so that it is reusable.首先,我创建了一个组件,以便它可以重用。

interface DynamicSelectProps {
    readonly id: string
    readonly options: any[]
    readonly defaultValue: string | null
    readonly disabled: boolean
    onSelectItem(item: any): any
    children?:React.ReactNode
}

export default function DynamicSelect({id, options, defaultValue, onSelectItem, disabled}: DynamicSelectProps) {

    const [selection, setSelection] = useState<any[]>([]);

    return <>
        <Typeahead
            labelKey={option => `${option.key}`}
            id={id}
            onChange={selected => {
                setSelection(selected)
                onSelectItem(selected)
            }}
            options={options}
            defaultInputValue={defaultValue || ""}
            placeholder="Search"
            selected={selection}
            disabled={disabled}
        />
    </>
}

Callback function回调函数

function onSelection(selection: any) {
    console.log(selection)
    //handle selection
}

Usage用法

<div className="form-group">
    <DynamicSelect
        options={array.map(item => <option key={item} value={item}>{item}</option>)}
        id="search-typeahead"
        defaultValue={<default-value>}
        disabled={false}
        onSelectItem={onSelection}>
    </DynamicSelect>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用引导程序创建带有带有标签的复选框列表的下拉菜单? - How do I create a drop down menu with a list of check boxes with labels using bootstrap? 如何仅使用 Javascript 创建动态下拉框? - How do I create a dynamic drop down box with just Javascript? 如何在 react-bootstrap 中实现溢出隐藏? - How do I implement overflow-hidden in react-bootstrap? 创建动态下拉列表 - Create dynamic Drop Down List 如何根据前一个下拉列表和最终选择显示文本框创建下拉列表 - How do I create a drop down list dependant on previous drop down and final choice displays text box 在React.js中,如何使用react-bootstrap创建链接以更改活动选项卡? - In React.js how do you create a link to change the active tab using react-bootstrap? 如何在 react 中使用 formik 创建动态下拉列表? - How to create dynamic drop down using formik in react? React react-bootstrap - 如何从外部组件关闭模态 window - React react-bootstrap - How do I close a modal window from an outside component 如何从数据库中的值在html中创建动态下拉列表? - How to create a dynamic drop down list in html from values in database? 如何在JavaScript / jQuery中创建动态SELECT下拉列表? - How to create a dynamic SELECT drop-down list in JavaScript/jQuery?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM