单击后如何从选择菜单中将特定选项显示为灰色?

时间:2019-04-09 08:43:52

标签: javascript reactjs redux

我有一个问题列表,我希望在单击某个特定选项后将其显示为灰色。现在,当我单击它时,整个选择列表显示为灰色(这不是我想要的)。如何实现呢?

我的带选择选项的下拉菜单:

    export function DropDownMenu(props) {

        let selectOption;

        if (props.questionOverviewList[props.index]) {
            selectOption = 
    props.questionOverviewList[props.index].map((item) =>
                <OptionList key={item._id} index={props.index} 
    question= . 
  {item.question}/>);
        }

        return <div className="panel panel-default">
            <div className="input-group mb-3">
                <div className="input-group-prepend">
                    <CategoryLabel title={props.categoryTitle}/>
                </div>
                <select className="custom-select" onClick={(e) => 
    e.target.disabled = true} 
                        onChange={(e) => . 
   props.selectedQuestionByTeamLeader(e.target.value)}>
                    <option></option>
                    {selectOption}
                </select>
            </div>
        </div>

    }

我的选择组件:

    export default function OptionList(props) {

        return <option>{props.question}</option>

    }

请注意,选项组件可重复使用。

1 个答案:

答案 0 :(得分:1)

这里是将所选项目_id存储到DropDownMenu状态的解决方案。 您必须通过浏览HTML选择元素选项从子选项组件中获取_id:

class DropDownMenu extends React.Component {

  constructor(props) {
    super(props);
    this.state = { selectedItemId: undefined };
  }

  optionSelected(selectElement) {
    let selectedOption;
    for (let option of selectElement.target.children) {
      if (option.value === selectElement.target.value) {
        selectedOption = option;
        break;
      }
    }

    this.setState({ selectedItemId: selectedOption.getAttribute('_id') });
    this.props.selectedQuestionByTeamLeader(selectedOption);
  }

  render() {
    const selectOption = this.props.questionOverviewList[this.props.index].map((item) => {
      console.log(this.state.selectedItemId === `${item._id}`);
      return <OptionList key={item._id} _id={item._id} index={this.props.index} question={item.question}
        grayedOut={this.state.selectedItemId === `${item._id}`} />
    });

    return <select className="custom-select" onChange={(e) => this.optionSelected(e)}>
      <option></option>
      {selectOption}
    </select>;
  }
}

然后根据OptionList grayedOut属性禁用属性:

function OptionList(props) {
  return <option disabled={props.grayedOut} _id={props._id}>{props.question}</option>
}

此JSFiddle显示它正在工作!

https://jsfiddle.net/poyea78q/