【问题标题】:Preventing close of select input on selection in React防止在 React 中关闭选择输入
【发布时间】:2017-01-06 06:18:08
【问题描述】:

如何防止<select> 元素在选择选项后自动关闭它的下拉列表,即即使在做出选择后我想保持选项下拉列表打开。

我尝试在onChange 处理程序中为<select> 调用event.stopPropagation()event.preventDefault(),但均未成功。

Here 是基本组件的一个小技巧。我想实现我上面描述的功能。

编辑:我尝试将stopPropagation()(在可能的重复项中提到)应用于<option> 的点击处理程序,但这也不起作用。对我来说,似乎有一种特定于 React 的方式来处理这种情况。

【问题讨论】:

标签: javascript html reactjs


【解决方案1】:

根据this answer 的说法,使用原生<select> 元素是不可能的——至少不像你所期望的那样。所以我看到了几种可能性:

  1. 使用无序列表或任何其他非表单元素创建一个“假”下拉菜单,如the answer that Jon Uleis pointed out in the comment above

  2. 如果您仍然喜欢使用原生的<select> 元素,可以使用slightly hacky approach 来设置change 上元素的size 属性(也可以选择在blur 上删除它)。

    以下是 React 中的一个简单示例:

class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isFocused: false };

    this.handleChange = this.handleChange.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
  }

  handleChange(e) {
    this.setState({ isFocused: true });
  }

  handleBlur(e) {
    this.setState({ isFocused: false });
  }

  render() {
    return (
      <select
        onChange={this.handleChange}
        onBlur={this.handleBlur}
        size={this.state.isFocused
          ? this.props.options.length
          : false}>
        {this.props.options.map((option, index) => (
          <option key={option}>{option}</option>
        ))}
      </select>
    );
  }
}

const options = [
  'This should “stay open”',
  'on change.',
  'It should also “collapse”',
  'on blur.'
];

ReactDOM.render(
  <Hello options={options} />,
  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"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 1970-01-01
    相关资源
    最近更新 更多