传入模板(children)
- 在组建中间写要传入的虚拟dom
- 在子组件中展示{this.props.children}
示例代码:
在components文件夹下创建Child3.js(给子组件传入一个模板):
父组件Index.js中:
import React, { Component } from 'react'
import Child1 from './components/Child1'
import Child2 from './components/Child2'
import Child3 from './components/Child3'
// 父组件 父组件向子组件传值
export default class One extends Component {
state = {
hello: '我是父组件的值'
};
// 这个回调函数 要在子组件中触发
callback(msg) {
console.log('父组件被触发')
// 括号里的形参msg也可写别的名字,
// 接收的是子组件传过来的值
console.log(msg)
}
render() {
// 对象结构方式,将state中的数据提取出来,赋值给另外的变量
// vue中一直是直接写:this.state.xxx
let { hello } = this.state;
// 对象结构
return (
<div>
{/* 给子组件绑定hello这个属性 */}
{/* 注意:等号右边的hello对应的是上面值的Hello,也就是要传的数据 */}
<Child1 hello={hello} />
{/* 给子组件绑定这个回调 */}
{/* this.callback对应的是上面callback函数 */}
<Child2 callback={this.callback} />
<Child3>
<div>
{/* 回到Child3.js子组件中,接收父组件里的代码 */}
<h1>我是父组件的代码</h1>
<h2>我是父组件的代码</h2>
<h3>我是父组件的代码</h3>
<h4>我是父组件的代码</h4>
<h5>我是父组件的代码</h5>
</div>
</Child3>
</div>
)
}
}
回到子组件Child3.js中:
// 传入模板
import React, { Component } from 'react'
export default class Child3 extends Component {
render() {
return (
<div>
{/* 使用this.porps.children接收父组件里的代码 */}
{this.props.children}
</div>
)
}
}
最后浏览器运行,模板传入成功: