中的子组件我想创建一个可重用组件,其中每次渲染组件时DOM结构都可能会有所不同。比方说,我有这个React.js渲染组件
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中的位置是动态的,并且可能会根据页面的布局而改变。 我想到了2个解决方案迄今:
迭代
props.children
里面,直到我找到感兴趣的元素,然后与物业克隆它使用
ref
并以某种方式使子组件的主要成分后已通过componentDidMount
回调呈现。
你对此有何看法?
你能突出你的问题吗? – divine