javascript - 处理受引用影响的状态的 react 方式是什么

标签 javascript reactjs

因此,现在有几次我需要根据渲染时计算的属性来设置组件的状态。因此,组件有时会被重新渲染。这不是一个大问题,但感觉很老套,而不是“ react 方式”。所以我想知道是否有人有更好的解决方案。

最近的例子是一个可扩展的文本组件。类似于airbnb上的评论元素

enter image description here

这相当简单。但最后一部分是检测是否有溢出,如果不需要则不显示“更多”选项。我想出的解决方案是检查scrollHeight是否大于clientHeight并基于此设置一些状态。这是我的解决方案的简化版本。

import React, { Component, PropTypes } from 'react';
import classNames from 'classnames'

function isOverflowed(element) {
  return element.scrollHeight > element.clientHeight;
}

export default class ExpandableText extends Component {
  static propTypes = {
    content: PropTypes.string,
    maxHeight: PropTypes.number,
  };

  static defaultProps = {
    isOpen: false,
    maxHeight: 10,
  }

  constructor(props) {
    super(props);

    this.handleOpen = this.handleOpen.bind(this);
    this.handleClose = this.handleClose.bind(this);

    this.state = {
      isOpen: props.isOpen,
      isOverFlowed: true,
    };
  }

  componentDidMount() {
    if (!isOverflowed(this.refs.content)) {
      this.setState({ isOpen: true, isOverFlowed: false });
    }
  }

  handleOpen() {
    this.setState({ isOpen: true });
  }

  handleClose() {
    this.setState({ isOpen: false });
  }

  render() {
    const { content, maxHeight } = this.props;
    const { isOpen, isOverFlowed } = this.state;
    const contentClassName = classNames('expandable-text', {
      'expandable-text__content--closed': !isOpen,
      'expandable-text__content--open': isOpen,
    });
    const actionsClassName = classNames('expandable-text__actions', { hide: !isOverFlowed })
    return (
      <div className="expandable-text">
        <div
          ref="content"
          className={contentClassName}
          style={{
            maxHeight: isOpen ? 'none' : `${maxHeight}rem`,
          }}
        >
			<p>{content}</p>
        </div>
        <div className={actionsClassName}>
          <button onClick={isOpen ? this.handleClose : this.handleOpen}>{isOpen ? 'Close': 'Open'}</button>
        </div>
      </div>
    );
  }
}

所以发生了相当多的事情,但重要的是在 componentDidMount 中,我正在检查溢出,然后基于此设置状态(可能)。

现在我意识到这可能可以通过允许限制字符数而不是高度或其他解决方案来实现。但如果我们假设解决方案与此类似,是否有更多的 react 方式来做到这一点? (这不需要重新渲染)

最佳答案

这很好!您必须先渲染文本,然后才能检测它是否会溢出。

你可以做一些奇怪的事情,比如计算字符/行数。但是每个客户端的字体大小可能会有很大差异,因此您最终只能对溢出大小进行“良好”猜测。

另一件事是首先将文本“离开 Canvas ”以某种方式/用户看不到的地方渲染到与目标容器行为相同的容器中。然后测量溢出并开始渲染到实际容器,知道它会/不会溢出。

关于javascript - 处理受引用影响的状态的 react 方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38493178/

相关文章:

javascript - Typeahead.js 和图像缩略图

javascript - 如何获取javascript中特定子元素的数量

node.js - 所有请求后服务器上的同构通量渲染

javascript - Meteor React Form 不会改变值

javascript - react : get Form values from children component on submit

java - React 和 Freemarker 集成

javascript - 如何解析我的 json 对象

javascript - 有没有办法让元素在 mousedown 事件激活之前消失?

javascript - 在 Firebase 函数 CLI 中模拟用户创建

javascript - Android WebView 在底部添加奇怪的空白区域