如何向组件内部动态传入带内容的结构(标签)?
Vue中:
使用slot技术, 也就是通过组件标签体传入结构
React中:
- 使用children props: 通过组件标签体传入结构
- 使用render props: 通过组件标签属性传入结构,而且可以携带数据,一般用render函数属性
正常的父子组件是这样写的:
import React, { Component} from 'react';
import './components/style.css'
class App extends Component {
state = {
count:10
}
render() {
const { count} = this.state;
return (
<div className='parent'>
<h2>我是APP组件</h2>
<h3>count当前的值是:{count}</h3>
<hr/>
<Child/>
</div>
);
}
}
class Child extends Component {
render() {
console.log('子组件调用render方法')
return (
<div className='child'>
<h2>我是Child组件</h2>
</div>
);
}
}
export default App;
1. children props
通过this.props.children接收父组件传过来的值。
import React, { Component} from 'react';
import './components/style.css'
class App extends Component {
state = {
count:10
}
render() {
const { count} = this.state;
return (
<div className='parent'>
<h2>我是APP组件</h2>
<h3>count当前的值是:{count}</h3>
<hr/>
<Child>
hello,我是父组件传过来的值
</Child>
</div>
);
}
}
class Child extends Component {
render() {
console.log('子组件调用render方法')
return (
<div className='child'>
<h2>我是Child组件</h2>
<h4>{this.props.children}</h4>
</div>
);
}
}
export default App;
import React, { Component} from 'react';
import './components/style.css'
class App extends Component {
state = {
count:10
}
render() {
const { count} = this.state;
return (
<div className='parent'>
<h2>我是APP组件</h2>
<h3>count当前的值是:{count}</h3>
<hr/>
<Child>
<Son/>
</Child>
</div>
);
}
}
class Child extends Component {
render() {
return (
<div className='child'>
<h2>我是Child组件</h2>
<h4>{this.props.children}</h4>
</div>
);
}
}
class Son extends Component {
render() {
return (
<div className='son'>
<h2>我是Son组件</h2>
</div>
);
}
}
export default App;
2. render Props
import React, { Component} from 'react';
import './components/style.css'
class App extends Component {
state = {
count:10
}
render() {
const { count} = this.state;
return (
<div className='parent'>
<h2>我是APP组件</h2>
<h3>count当前的值是:{count}</h3>
<hr/>
<Child render={() => <Son/>}/>
</div>
);
}
}
class Child extends Component {
render() {
return (
<div className='child'>
<h2>我是Child组件</h2>
{this.props.render()}
</div>
);
}
}
class Son extends Component {
render() {
return (
<div className='son'>
<h2>我是Son组件</h2>
</div>
);
}
}
export default App;
import React, { Component} from 'react';
import './components/style.css'
class App extends Component {
state = {
count:10
}
render() {
const { count} = this.state;
return (
<div className='parent'>
<h2>我是APP组件</h2>
<h3>count当前的值是:{count}</h3>
<hr/>
<Child render={(name, age) => <Son name={name} age={age}/>}/>
</div>
);
}
}
class Child extends Component {
state = {
name:'IRIC',
age:23
}
render() {
const {name, age} = this.state
return (
<div className='child'>
<h2>我是Child组件</h2>
{this.props.render(name, age)}
</div>
);
}
}
class Son extends Component {
render() {
return (
<div className='son'>
<h2>我是Son组件</h2>
<h3>姓名:{this.props.name}</h3>
<h3>年龄:{this.props.age}</h3>
</div>
);
}
}
export default App;