输入搜索框转换(宽度)不平滑

时间:2018-02-19 09:21:00

标签: css reactjs css-transitions

我正在尝试在焦点上展开输入搜索框,并在搜索框中失去焦点时将其压缩到原始状态。我能够使用css转换实现相同的功能。但有些时候我看到过渡并没有顺利进行,如例子中所示。有没有最好的方法来实现同样的目标?或者对我的代码提出任何建议以实现顺畅。

虽然扩展它会导致兄弟组件也重新渲染,因为它正在扩展它。

反应代码:

 <div className="header" style={{ width: "420px"}} ref={(searchHeader) => { this._searchHeader = searchHeader }}>
      <label className="label">{"Search here"}</label>
      <div className="SearchBox">
           <input className="input" spellCheck={false} onFocus={this.onFocus} onBlur={this.onBlur} />
           <div className="search-icon">
                <span className="Search-icon" />
          </div>
      </div>
 </div>




private onFocus = (): void => {
        if (this._searchHeader) {
            this._searchHeader.style.width = "1000px";
        }
    }

    private onBlur = (): void => {
        if (this._searchHeader) {
            this._searchHeader.style.width = "420px";
        }
    }

CSS:

.label{
        width: 110px;
        padding-top: 6px;
        padding-left: 10px;
        padding-right: 10px;
        white-space: nowrap;
        background: rgba(255, 255, 255, 0.5);
}

.header {
        display: flex;
        align-items: stretch;
        flex-shrink: 0;
        -webkit-transition: width 2s linear; /* Safari*/
        transition: width 2s linear;
}

.input{
        align-self: stretch;
        min-width: 200px;
        padding: 0 6px;
}

1 个答案:

答案 0 :(得分:0)

我创建了一个代码框来解决您的问题。请检查这是否适合您。

请不要使用refs,而是使用state。

  onFocus() {
    // console.log('OnFocus', this);
    this.setState({
      isFocused: true
    })
  }

  onBlur() {
    // console.log('onBlur', this);
    this.setState({
      isFocused: false
    })
  }

https://codepen.io/Harsh89/pen/GQQPxK?editors=1111