- 在父组件中
import React, { Component } from "react";
import Child from './child'
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
top: "--------------- 上 --------------------",
bottom: "--------------- 下 --------------------",
defaultContent: "默认插槽内容",
namedContent: "具名插槽内容",
};
}
render() {
return (
<>
<h1>react 插槽</h1>
<div>{this.state.top}</div>
<Child namedSlot={<div>{this.state.namedContent}</div>}> {/* 具名插槽 */}
<div>{this.state.defaultContent}</div> {/* 默认插槽 */}
</Child>
<div>{this.state.bottom}</div>
</>
);
}
}
export default Parent;
- 在子组件中
import React, { Component } from "react";
class Child extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<>
<div>{this.props.children}</div> {/* 定义默认插槽位置 */}
<div>{this.props.namedSlot}</div> {/* 定义具名插槽位置 */}
</>
);
}
}
export default Child;
网友评论