【问题标题】:hiding a form input on click outside of its onlclick div在其 onclick div 之外隐藏单击时的表单输入
【发布时间】:2018-07-15 23:40:02
【问题描述】:

我有一个由一个输入组成的表单,我想切换它。单击 div 时会显示该表单,而当我单击 div 之外时,我想隐藏该表单。我如何在 React 中做到这一点?

class InputToggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showInputForm: false
    };
  }
  onClickAction(e) {
    e.preventDefault();
    this.setState({ showInputForm: true });
  }
  render() {
    if (this.state.showInputForm) {
      return (<input type="text" />)
    }
    return (
      <div onClick={this.onClickAction.bind(this)}>
        <h1>value</h1>
      </div>
    );
  }
}

如何在div 之外单击时将状态showInputForm 设置为false?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您必须在输入元素上使用onBlur 事件监听器。见代码:

    class InputToggle extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          showInputForm: false
        };
      }
      onClickAction(e) {
        e.preventDefault();
        this.setState({ showInputForm: true });
      }
      componentDidUpdate() {
        if (this.state.showInputForm) {
          this.input.focus();
        }
      }
      render() {
        if (this.state.showInputForm) {
          return (
            <input
              ref={(el) => this.input = el}
              onBlur={() => this.setState({ showInputForm: false })}
              type="text" />
          );
        }
        return (
          <div onClick={this.onClickAction.bind(this)}>
            <h1>value</h1>
          </div>
        );
      }
    }
    

    请注意,我必须在渲染时聚焦输入。如果输入不在焦点上,则不会触发 onBlur 事件。

    查看工作pen

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-26
      • 2013-08-28
      • 1970-01-01
      • 2012-07-17
      • 2011-09-20
      • 2014-09-08
      • 2013-04-18
      相关资源
      最近更新 更多