代码之家  ›  专栏  ›  技术社区  ›  Tristan Trainer Ferguson Osas

有没有办法在reactjs中设置元素的初始高度?

  •  1
  • Tristan Trainer Ferguson Osas  · 技术社区  · 6 年前

    我有一个react组件,它允许根据内部文本调整文本区域的大小。

    return (<div className={`resizable-textbox ${className}`}>
       <textarea
          value={value}
          onChange={onChangeMade}
          onBlur={onBlur}
          readOnly={readOnly} />
    </div>);
    

    onChangeMake方法如下所示:

    const onChangeMade = (e) => {
      const scrollHeightPadded = e.target.scrollHeight;
    
      if ((scrollHeightPadded + "px") !== e.target.style.height) {
        e.target.style.height = 0;
        const height = Math.max(scrollHeightPadded, 31) + 3;
        e.target.style.height = `${height}px`;
      }
    }
    

    我知道这个方法有点难看,需要清理一下。但是,我想在第一次加载组件时调用此方法,但是 e 是由 textarea 标签。

    有没有方法可以直接连接到这个或 component 用这种方法?(我正在使用) React Hooks 无国籍的 components )

    谢谢。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Tholle    6 年前

    你可以使用 createRef 创建一个ref并将其交给 ref 你的支柱 textarea 用它代替事件。

    例子

    class MyComponent extends React.Component {
      ref = React.createRef();
    
      componentDidMount() {
        this.onChangeMade();
      }
    
      onChangeMade = () => {
        const { current } = this.ref;
        const scrollHeightPadded = current.scrollHeight;
    
        if (scrollHeightPadded + "px" !== current.style.height) {
          current.style.height = 0;
          const height = Math.max(scrollHeightPadded, 31) + 3;
          current.style.height = `${height}px`;
        }
      };
    
      render() {
        return (
          <div className={`resizable-textbox ${className}`}>
            <textarea
              ref={this.ref}
              value={value}
              onChange={onChangeMade}
              onBlur={onBlur}
              readOnly={readOnly}
            />
          </div>
        );
      }
    }