简体   繁体   English

如何使用 .append() 将 React 组件附加到 HTML 元素

[英]How to append React components to HTML element using .append()

I am trying to implement infinite-scroll to my blog, I have我正在尝试对我的博客实施无限滚动,我有

const articlesHTML = document.querySelector(".articles");

as container.作为容器。 On each click on Load more button I want to append the new articles to the main html element, like this:每次单击“加载更多”按钮时,我都想将新文章附加到主 html 元素,如下所示:

const results = articles
      .slice(0, 10 * pager)
      .map((articleID, i) => (
        <Article key={i} id={articleID} />
      ));
articlesHTML.append(results);

however, results is bunch of <Article/> react components not html nodes, am I missing something?然而, results是一堆<Article/>反应组件而不是 html 节点,我错过了什么吗?

You could use render from ReactDOM to render the components into a hidden HTML node and then append the contents of that node to another node.您可以使用ReactDOM中的render将组件渲染到隐藏的 HTML 节点中,然后将该节点的内容附加到另一个节点。

But using React's output like that is generally a bad idea .但是像那样使用 React 的输出通常不是一个好主意 What I would suggest is building the entire component in React.我的建议是在 React 中构建整个组件。

For example:例如:

const App = () => {
    const [articles, setArticles] = useState([]);
    const loadMore = useCallback(() => {
        setArticles(...);
    }, [setArticles]);

    return (
        <div className="app">
             {articles.map((article) => <Article key={article.uuid} ... />)}
             <button onClick={loadMore}>Load more</button>
        </div>
    );
};

You can try like this by using Array.slice() - Demo您可以使用Array.slice()尝试这样 -演示

class Home extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      lists: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
      limit: 3
    };
  }
  addMore = () => this.setState(prev => ({ limit: prev.limit + 3 }));
  render() {
    const { lists, limit } = this.state;
    return (
      <div>
        {lists.slice(0, limit).map(list => (
          <p style={{ background: "lightgrey" }} key={list}>
            {list}
          </p>
        ))}
        {limit !== lists.length && (
        <button onClick={this.addMore}>Load More</button>
        )}
      </div>
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM