【问题标题】:React Clamp.js does not get applied when content loaded asynchronously异步加载内容时未应用 React Clamp.js
【发布时间】:2018-01-31 17:35:59
【问题描述】:

我正在使用 react clamp https://www.npmjs.com/package/react-clamp,它在幕后使用了 clamp.js。

this.props.events.map((event,i) => {
    return <div key={i}>
        <Clamp clamp={2}>The is a really long event name</Clamp>
    </div>
})

如果 this.props.events 是静态设置的,这会很有效,但是这些事件是异步获取的,并且在加载时会渲染这些事件。由于某种原因,Clamp 没有被重新应用。这可能与事件侦听器在第二次渲染时没有正确绑定有关吗?

更新 查看代码,它呈现没有更改的元素,并且在调用 componentDidUpdate 之前不应用钳位。当我在静态获取它的道具的元素上使用clamp时,会调用componentDidUpdate(尽管我不确定为什么,因为我看不到元素会更新的任何原因。当数据来自redux时,componentDidUpdate是从未调用过,因此不应用clamp。这可能与react-redux实现componentShouldUpdate有关吗?

【问题讨论】:

  • 您是否检查过您的组件中的this.props.events 是否已更改? this.props.events 变化在哪里?
  • 是的,其他一切都更新得很好。它只是没有应用的夹子。 this.props.events 用 redux 加载到父组件中并传递下去。

标签: javascript reactjs react-redux clamp


【解决方案1】:

最终编写了我自己的组件以直接使用clamp.js,它运行良好。组件安装后立即触发clamp.js。这些组件不会有任何更新,所以我没有实现 componentDidUpdate,但我可以轻松实现。

class Clamp extends Component {

    componentDidMount(){
        if (this.container.length) {
            throw new Error('Please provide exactly one child to clamp');
        }

        clamp(this.container, {
            clamp: this.props.clamp,
            truncationChar: this.props.truncationChar,
            useNativeClamp: this.props.useNativeClamp
        });
    }

    render() {
        return (
            <div ref={(div) => this.container = div}>{this.props.children}</div>
        );
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多