【发布时间】:2019-01-26 23:00:13
【问题描述】:
我见过与此类似的问题,但他们通常是在谈论父组件访问子组件的方法或通过 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>
)
}
}
以及调用所述组件并将子组件作为道具传递的组件。
const Component = (props) => {
return(
<WrapperComponent>
<div className="form-group" >
<label>
<div>Text</div>
<input onChange={this.handleInputChange} type={"text"}/>
</label>
</div>
</WrapperComponent>
)
}
我的想法是我可以渲染一个包含某些逻辑的组件,并将元素作为子元素传递给该组件以供渲染,而且props.children 然后可以在包装器中调用所述逻辑,所以我可以通过在不同用例中的不同子级中,但处理方式始终相同。有没有办法做到这一点?
【问题讨论】:
-
只要通过 props 传递给子组件即可。
标签: javascript reactjs methods