【问题标题】:How to use Masonry.js and React.js?如何使用 Masonry.js 和 React.js?
【发布时间】:2016-11-15 11:33:07
【问题描述】:

我正在尝试将 masonry.js 集成到 react.js 中,但我遇到了设计问题。

我是否应该将所有砌体块都放在一个根反应组件中,就像它在 react-masonry-component 中所做的那样

<RootComponent>
    this.props.elements.map(function(element){
           return (
                <li className="image-element-class">
                    <img src={element.src} />
                </li>
            );
        });
<RootComponent>

或者我应该将每个砌体块作为一个新的 React 组件作为根 React 组件的子组件?

<RootComponent>
    this.props.elements.map(function(element){
           return (
                <ChildComponent props={element}>
            );
        });
<RootComponent>

【问题讨论】:

  • 为什么不使用 react-masonry-component

标签: reactjs jquery-masonry react-masonry


【解决方案1】:

react-masonry-component 如果你想一直使用 masonry 是很好的,但是如果你想根据一些条件初始化 masonry,你可以这样做:

例如,您获取一些项目,然后初始化砌体:

componentWillMount() {
    this.props.fetchItems();
}

componentDidUpdate(prevProps) {
    const {
        items
    } = this.props;

    if (this.state.masonry && prevProps.items !== items) { // reinitialize if items change
        $('.list').masonry('destroy');

        this.setState({
            masonry: false
        });
    }

    if (someCondition && items.length && !this.state.masonry) {
        $('.list').masonry({
            itemSelector: '.list__item'
        });

        this.setState({
            masonry: true
        });
    }
}

你的渲染可以是这样的

render() {
const {
    items
} = this.props;
return (
    <div className="list">
        {items.map(item =>
            <div className="list__item" key={item.id} >
                {item.title}
            </div>
        )}
    </div>
);

}

【讨论】:

    猜你喜欢
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多