![](/img/trans.png)
[英]React.js: Difference between passing in the subcomponents with React.render() and with React.createClass()'s render?
[英]React.js render subcomponents from component
我想創建一個可重用的組件,每次呈現該組件時DOM結構都可以不同。 假設我有這個
class Comp extends React.Component {
constructor() {
super()
this.state = {
click: null,
}
}
render() {
return(
<div>
{this.props.chidren}
</div>
)
}
handleButton1() {
this.setState({click: 'button1'});
}
handleButton2() {
this.setState({click: 'button2'});
}
}
class SubComp1 extends React.Component {
render() {
return(
<button onClick={() => this.props.handleButton1()}>Button 1</button>
)
}
}
class SubComp2 extends React.Component {
render() {
return (
<button onClick={() => this.props.handleButton2()}>Button 2</button>
)
}
}
ReactDOM.render((
<Comp>
<div id="somediv">
<div id="andanother">
<SubComp1 />
</div>
</div>
<div id="andanotherother">
<SubComp2 />
</div>
</Comp>), document.getElementById('app'))
當前,這兩個子組件無法訪問它們各自的處理程序功能。 假設將函數handleButton1
和handleButton2
傳遞給子組件的最佳方法是,假設它們在DOM中的位置是動態的,並且可能會根據頁面的布局而變化。 到目前為止,我已經想到了兩種解決方案:
在props.children
內部進行迭代,直到找到感興趣的元素,然后使用屬性將其克隆
在通過componentDidMount
回調呈現主要組件之后,使用ref
和以某種方式呈現子componentDidMount
。
您對此有何想法?
為什么不做這樣的事情:
class Comp extends React.Component {
constructor() {
super()
this.state = {
click: null,
}
}
render() {
return(
<div>
{this.props.chidren}
</div>
)
}
handleButton(button) {
this.setState({click: button});
}
}
然后,在子組件中,您可以執行以下操作
class SubComp1 extends React.Component {
render() {
return(
<button onClick={() => this.props.handleButton('button1')}>Button 1</button>
)
}
}
class SubComp2 extends React.Component {
render() {
return (
<button onClick={() => this.props.handleButton('button2')}>Button 2</button>
)
}
}
一個可能滿足您需求的替代方法是構建一個更高階的組件,該組件用其他一些功能來裝飾另一個組件,下面是一個簡單的示例,說明了該組件如何為您工作,
高階部分:
const Comp = ComposedComponent =>
class Comp extends React.Component {
constructor(props) {
super(props)
this.handleButton = this.handleButton.bind(this);
this.state = {
click: null,
}
}
handleButton(button) {
this.setState({click: button});
}
render() {
return(
<ComposedComponent
onClick={this.handleButton}
/>
)
}
}
export default Comp;
子組件:
class SubComp1 extends React.Component {
render() {
return(
<button onClick={() => this.props.onClick('button1')}>Button 1</button>
)
}
}
如何使用它:
const ExtendedComp = Comp(SubComp1);
<ExtendedComp />
這適合您的任務嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.