How to use React Portal?

我只是一个虾纸丫 提交于 2021-02-11 14:16:56

问题


I am trying to use React Portal functionality, but can't seem to get it to work (am using React v16.2 and ReactDOM v16.2). In the example below, when I click the 'click me' link 'yey!' should appear but it doesn't:

HTML:

<div id="app-root"></div>
<div id="toast-root"></div>

JavaScript:

const appRoot = document.getElementById('app-root');

const insertToast = (toastRoot) => ReactDOM.createPortal(
  'yey!',
  toastRoot,
); 

class App extends React.Component {

  insertToasts() {
    const toastRoot = document.getElementById('toast-root');
    insertToast(toastRoot);
  }

  render() {
    return (
      <div>
        <a onClick={this.insertToasts}>click me</a>
      </div>
    );
  }
}

ReactDOM.render(<App />, appRoot);

回答1:


In your example, you create and return the portal from insertToast, however, you don't do anything with it - you need to return it and ensure that it is included within your render method:

const appRoot = document.getElementById('app-root');

const insertToast = (toastRoot) => ReactDOM.createPortal(
    'This is in toast-root - yey!',
    toastRoot,
);

class App extends React.Component {

    insertToasts() {
        const toastRoot = document.getElementById('toast-root');
        return insertToast(toastRoot);
    }

    render() {
        return (
            <div>
                <div>This is in app-root.</div>
                {this.insertToasts()}
            </div>
        );
    }
}

ReactDOM.render(<App />, appRoot);

Even if it's not being rendered in the same DOM as the component, you still have to tell React that you want to render it.



来源:https://stackoverflow.com/questions/49392236/how-to-use-react-portal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!