本文摘自PHP中文网,作者V,侵删。
react中的portal可以将子组件渲染到非父组件的子树下,同时父组件仍能对子组件做出反应;使用方法如【ReactDOM.createPortal(this.props.children, this.el);】。
本文环境:windows10、react16,本文适用于所有品牌的电脑。
作用:
将子组件渲染到非父组件的子树下,同时父组件仍能对子组件做出反应,我们甚至不用做过多的dom处理。
(学习视频分享:react视频教程)
举例:
现在有两个组件,Dog和Cat,我们想让Dog的子组件Puppy放到Cat里,当欺负Puppy的时候,即使相隔千里Dog也能感受到。
代码实现:
先获取页面中Dog窝和Cat窝
1 2 | const dogRoot = document.getElementById( "dog-house" );
const catRoot = document.getElementById( "cat-house" );
|
创建一个Puppy组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Puppy extends React.Component {
constructor(props) {
super(props);
this.el = document.createElement( "div" );
}
componentDidMount() {
catRoot.append(this.el);
}
componentWillUnmount() {
catRoot.removeChild(this.el);
}
render() {
return ReactDOM.createPortal(this.props.children, this.el);
}
}
|
创建Dog组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | class Dog extends React.Component {
constructor(props) {
super(props);
this.state = { bark: 0 };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState((state) => ({
bark: state.bark + 1,
}));
}
render() {
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);
|
再创建一个代替欺负Puppy的按钮组件
1 2 3 4 5 6 7 | function Bully(props) {
return (
<>
<button>Bully the {props.target}</button>
</>
);
}
|
相关推荐:js教程
以上就是react中的portal是做什么的的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
React grommet是什么
React子组件怎么向父组件传值?
React中间件的thunk和saga区别是什么
2021年前端React面试题大汇总(收藏)
React需要node吗
vue 和 React 的优点有哪些
React创建组件的三种方式分别是什么
怎么解决webstrom写React代码报错问题
React如何控制显示与隐藏
React中如何引入插件
更多相关阅读请进入《React》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » react中的portal是做什么的