如何使用redux从深层嵌套的子组件调用父组件中的函数 [英] How to invoke a function in parent component from deeply nested child component using redux
问题描述
class Parent 扩展 React.Component{构造函数(道具){超级(道具);this.clicked = this.clicked.bind(this);}getChildrenValues(){console.log("儿童价值观");}使成为(){返回 家长<组件1><组件2><孩子/></组件2></组件1>}}class Child 扩展 React.Component{构造函数(道具){超级(道具);this.clicked = this.clicked.bind(this);}点击(){this.props.dispatch({type: "InvokeParent"});}使成为(){返回
<button onClick = {this.clicked}>点击这里</button>}}
如何从Child"组件调用 getChildrenValues 函数.我试图从父组件获取所有子值并提交,但我不知道如何在 redux 中触发该函数.在不断变化中,我曾经做过 addChangeListener 并触发该功能.
仅根据您的示例,我会说这种情况根本不会涉及 redux.Redux 是一个管理全局状态的工具.此示例中没有任何内容是触摸状态.
对于此示例代码,将您的方法作为道具传递并在单击时调用它.如果取决于子组件的嵌套方式,这可能会很混乱.
class Parent 扩展 React.Component{构造函数(道具){超级(道具);this.clicked = this.clicked.bind(this);}getChildrenValues(){console.log("儿童价值观");}使成为(){返回 家长<组件1><组件2><Child invokeParent={this.getChildrenValues}/></组件2></组件1>}}class Child 扩展 React.Component{构造函数(道具){超级(道具);this.clicked = this.clicked.bind(this);}点击(){this.props.dispatch({type: "InvokeParent"});}使成为(){返回
<button onClick = {this.props.invokeParent}>点击这里</button>}}
class Parent extends React.Component{
constructor(props){
super(props);
this.clicked = this.clicked.bind(this);
}
getChildrenValues(){
console.log("Children values");
}
render(){
return <div>
Parent
<Component1>
<Component2>
<Child />
</Component2>
</Component1>
</div>
}
}
class Child extends React.Component{
constructor(props){
super(props);
this.clicked = this.clicked.bind(this);
}
clicked(){
this.props.dispatch({type: "InvokeParent"});
}
render(){
return <div>
<button onClick = {this.clicked}>Click Here</button>
</div>
}
}
how to invoke getChildrenValues function from "Child" component. I am trying to get all children values from parent component and submit but I do not know how to trigger that function in redux. In flux I used to do addChangeListener and trigger that function.
Just based on your example, I would say this situation won't involve redux at all. Redux is a tool for managing global state. Nothing in this example is touching state.
For this example code to work pass your method down as a prop and invoke it on click. This can be messy if depending on how nested the child component is.
class Parent extends React.Component{
constructor(props){
super(props);
this.clicked = this.clicked.bind(this);
}
getChildrenValues(){
console.log("Children values");
}
render(){
return <div>
Parent
<Component1>
<Component2>
<Child invokeParent={this.getChildrenValues} />
</Component2>
</Component1>
</div>
}
}
class Child extends React.Component{
constructor(props){
super(props);
this.clicked = this.clicked.bind(this);
}
clicked(){
this.props.dispatch({type: "InvokeParent"});
}
render(){
return <div>
<button onClick = {this.props.invokeParent}>Click Here</button>
</div>
}
}
这篇关于如何使用redux从深层嵌套的子组件调用父组件中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!