Portal in react can render child components to a subtree of non-parent components, while the parent component can still react to the child components; the usage method is such as [ReactDOM.createPortal(this.props.children, this.el);].
The environment of this article: windows10, react16, this article is applicable to all brands of computers.
Function:
Render the child component to a subtree of a non-parent component. At the same time, the parent component can still react to the child component. We don't even need to do too much DOM processing.
(Learning video sharing: react video tutorial)
Example:
Now there are two components, Dog and Cat, we want Dog The subcomponent Puppy is placed in Cat. When Puppy is bullied, Dog can feel it even if it is thousands of miles away.
Code implementation:
First get the Dog nest and Cat nest in the page
const dogRoot = document.getElementById("dog-house"); const catRoot = document.getElementById("cat-house");
Create a Puppy component
class Puppy extends React.Component { constructor(props) { super(props); // 创建一个容器标签 this.el = document.createElement("div"); } componentDidMount() { // 把容器标签挂到 catRoot DOM下 catRoot.append(this.el); } componentWillUnmount() { catRoot.removeChild(this.el); } render() { // 利用portal把Puppy的内容放到容器里 return ReactDOM.createPortal(this.props.children, this.el); } }
Create Dog component
class Dog extends React.Component { constructor(props) { super(props); this.state = { bark: 0 }; this.handleClick = this.handleClick.bind(this); } handleClick() { // 点击的时候 bark + 1 this.setState((state) => ({ bark: state.bark + 1, })); } render() { // 看上去Puppy组件是在Dog挂在Dog组件里,但其实它被挂载在其它地方 return ( <div onClick={this.handleClick}> <p>The number of times a big dog barks: {this.state.bark}</p> <h3>Dog: </h3> <p>I can't see my children, but I can feel them</p> <Puppy> <Bully target={'Puppy'}/> </Puppy> <Bully target={'Dog'}/> </div> ); } } ReactDOM.render(<Dog />, dogRoot);
Create another button component to replace bullying Puppy
function Bully(props) { return ( <> <button>Bully the {props.target}</button> </> ); }
Related recommendations: js tutorial
The above is the detailed content of What does the portal in react do?. For more information, please follow other related articles on the PHP Chinese website!