我知道这个问题已经在堆栈溢出中得到了解决,但对我来说,我有更具体的要求。我想在子comp中定义道具的值,并能够将其值传递给其祖父母comp。要定义值的子组件:
const Child = React.createClass(
onselect(status) {
let testProp = {refs: this.refs.statetext, status:status}
}
render() {
return (
<Mycomp ref="statetext"/>
);
});
家长:
const Parent = React.createClass(
//can I access the refs.statetext here???
render() {
return (
<Child/>
);
});
爷爷奶奶:
const GrandParent = React.createClass(
//here I'd like to access the testProp defined in the Child comp
closeMenu() {
//should have the testProp value here to do some action in this function.
}
render() {
return (
<Parent onScroll={this.closeMenu.bind(this)}/>
);
});
这有可能吗??
似乎您只需要一个事件,它将流向老爷子
组件。在React中,props
向下流动,事件
向上流动。所以,下面的代码,通过父
将onSelect
事件冒泡到祖父
:
const Child = React.createClass(
onselect(status) {
let testProp = {refs: this.refs.statetext, status:status}
this.props.onSelect(testProp);
}
render() {
return (
<Mycomp ref="statetext"/>
);
});
然后:
const Parent = React.createClass(
//here I'd like to access the testProp defined in the Child comp
render() {
return (
<Child onSelect={this.props.onSelect} />
);
});
然后:
const GrandParent = React.createClass(
//here I'd like to access the testProp defined in the Child comp
closeMenu() {
//should have the testProp value here to do some action in this function.
}
onSelect(testProp) {
// here it is :)
// you can now save it in state, so it will be available when the menu is closed.
console.log(testProp);
}
render() {
return (
<Parent onScroll={this.closeMenu.bind(this)} onSelect={this.onSelect.bind(this)} />
);
});
声明/初始化爷爷
组件中的变量,并通过道具将其传递给孩子
。
这就是表示/容器组件的要点。如果你的子
组件依赖于祖父
组件,那就是你的状态应该存在的地方。