props children 和容器類組件
先做出容器
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import './index.css'
class Card extends Component {
render() {
return (
<div className='card'>
<div className='card-content'>
{this.props.content}
</div>
</div>
)
}
}
ReactDOM.render(
<Card content={
<div>
<h2>React 小書</h2>
<div>開源、免費、專業、簡單</div>
訂閱:<input />
</div>
} />,
document.getElementById('root')
)
將 props.children 印出來
React.js 就是一個個把 JSX 元素放到 array 當中,故也可用陣列方法把 JSX 放在不同地方。
class Layout extends Component {
render () {
return (
<div className='two-cols-layout'>
<div className='sidebar'>
{this.props.children[0]}
</div>
<div className='main'>
{this.props.children[1]}
</div>
</div>
)
}
}
利用實用的 props.children 撰寫
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import './index.css'
class Card extends Component {
handleLog() {
console.log(this.props.children)
}
render() {
return (
<div className='card'>
<div className='card-content' onClick={this.handleLog.bind(this)}>
{this.props.children}
</div>
</div>
)
}
}
ReactDOM.render(
<Card>
<h2>React.js 小書</h2>
<div>開源、免費、專業、簡單</div>
訂閱:<input />
</Card>,
document.getElementById('root')
)