反应选择不识别默认值 [英] react select not recognizing default value

查看:50
本文介绍了反应选择不识别默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无法选择默认值选项的react select组件.代码如下:

I have a react select component that isn't recognizing the default value option. The code looks like this:

renderPlans(){
        if(this.props.plans){
            let list =  this.props.plans.map(item=>{
                return ({label:item.description, value:item.id})
            });

            return(
                <Select
                    name= "tile-plans"
                    value= {this.state.selected}
                    classNamePrefix='react-select-container'
                    options={list}
                    defaultValue={list[0]}
                    onChange={(e) => { e ? this.setState({selected: e.value}) : this.setState({selected: ''}) }}
                />
            )
        }
    }

从我可以在其文档中找到的所有内容中

,这就是给出它的格式.基本上,我只是希望第一个选项始终是默认选项,因为有时只有一个选项,而对于某个人来说,选择下拉菜单是没有意义的.我下面还有一个要加载的图形,因此,如果选择了某个选项,则该图形将不会加载.

from everything I can find on its docs this is the format to give it. Basically I just want the first option to always be the default choice as there will be times when there is only 1 option and it doesn't make sense for someone to need to select a drop down. I also have a graph that's being loaded underneath so if an option is selected the graph won't load.

这不是重复的问题,因为我知道您可以这样做: value = {this.state.selected?this.state.selected:list [0] .label} 但它不起作用.输入在加载时保持空白.

This isn't a duplicate question as I know you can do it like this: value= {this.state.selected ? this.state.selected:list[0].label} but it's not working. The input remains blank on load.

推荐答案

文档指出:如果不提供这些道具,则可以设置其控制的状态的初始值",并引用值道具.

The documentation states that "If you don't provide these props, you can set the initial value of the state they control", referencing among others the value prop you provide.

创建组件时,可以将 selected 设置为 list 中的第一个元素.

You can set the selected to the first element in list when the component is created instead.

示例

class App extends React.Component {
  state = {
    selected: this.props.list[0]
  };

  handleChange = selected => {
    this.setState({ selected });
  };

  render() {
    const { selected } = this.state;

    return (
      <Select
        value={selected}
        onChange={this.handleChange}
        options={this.props.list}
      />
    );
  }
}

ReactDOM.render(
  <App
    list={[
      { value: "chocolate", label: "Chocolate" },
      { value: "strawberry", label: "Strawberry" },
      { value: "vanilla", label: "Vanilla" }
    ]}
  />,
  document.getElementById("root")
);

这篇关于反应选择不识别默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆