我见过类似的问题,但他们通常谈论的是父组件访问子组件的方法或通过 props 传入方法。我的问题是针对特定情况,使用 props.children
,并且让任何子组件都能够调用正在渲染 props.children
的父组件上的方法。
我想要实现的目标的简化示例:
class WrapperComponent extends React.Component {
constructor(props){
super(props);
this.handleInputChange = this.handleInputChange.bind(this)
}
handleInputChange(e){
console.log("neat, you changed the input")
}
render() {
return (
<form>
{this.props.children}
</form>
)
}
}
以及调用所述组件并将子组件作为 Prop 传递的组件。
const Component = (props) => {
return(
<WrapperComponent>
<div className="form-group" >
<label>
<div>Text</div>
<input onChange={this.handleInputChange} type={"text"}/>
</label>
</div>
</WrapperComponent>
)
}
这个想法是,我可以渲染一个包含特定逻辑的组件,并将元素作为子元素传递给该组件进行渲染,而且 props.children
然后可以在其中调用所述逻辑包装器,因此我可以在不同的用例中传递不同的子级,但处理始终是相同的。有办法做到这一点吗?
最佳答案
您可以克隆元素并使用一些内置的 React 功能向它们添加新的 props:
class WrapperComponent extends React.Component {
constructor(props){
super(props);
this.handleInputChange = this.handleInputChange.bind(this)
}
handleInputChange(e){
console.log("neat, you changed the input")
}
render() {
return (
<form>
{React.Children.map(
this.props.children,
el => React.cloneElement(el, {onInputChange: this.handleInputChange})
)}
</form>
)
}
}
然后(删除 WrapperComponent):
const Component = (props) => {
return(
<div className="form-group" >
<label>
<div>Text</div>
<input onChange={props.onInputChange} type={"text"}/>
</label>
</div>
)
}
然后:
ReactDOM.render(
<WrapperComponent><Component /></WrapperComponent>,
document.getElementById('root')
)
关于javascript - 子组件可以访问其包含组件的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51937099/