【问题标题】:React compose prevent div wrapReact compose 防止 div 换行
【发布时间】:2019-01-13 15:33:49
【问题描述】:

我在 React 中有一个简单的组件:

const applyFallbackStyles = withFallbackStyles( ( node, ownProps ) => {
  const { imageWidth } = ownProps;
  const divNode = node.querySelector( '.text' );
  return {
    fallbackImageWidth: getComputedStyle( divNode ).width,
  };
} );


class Image extends Component {
    constructor( props ) {
        super( ...arguments )
    }

    render() {
       <div className="test">Hello world</div>
    }
 }

并使用 compose 包装函数

export default compose( [
    applyFallbackStyles,
] )( Image );

组件渲染:

<div>
   <div className="test">Hello world</div>
</div>

为什么要添加额外的 div? compose 似乎将&lt;div className="test"&gt;Hello world&lt;/div&gt; 包装在另一个&lt;div&gt; 中

可以避免吗?或者至少为它指定一个类名。

【问题讨论】:

标签: reactjs higher-order-components


【解决方案1】:

我从该库的源代码中了解到,您需要将节点引用指定为组件的道具,否则默认情况下会添加 div。为了避免这种情况,也许你可以这样做

1) 用 div 包装你的组件并从该元素中获取 ref

2)将该元素设置为图像元素的节点道具

class App extends React.Component{
  node = null;
  render() {
    <div ref={el => this.node = el} className="test">
      <Image node={this.node} />
    </div>
  }
}

【讨论】:

  • 嗯,我试过了,但它仍在添加 div。 this.node 似乎正在返回 div 测试及其中的所有内容。我猜这是意料之中的?
  • 你有正在运行的版本可以查看吗?
  • 请查看更新后的代码。我添加了 applyFallbackStyles 函数,用于获取样式属性值。我没有运行版本
  • 你能在这里发布你的组件的完整代码吗?我尝试使用 lib,但我得到 regeneratorRuntime undefined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-04
相关资源
最近更新 更多