我知道问题已在堆栈溢出中得到解决,但对我来说,我有更具体的要求。我想在子comp中定义一个prop的值,并能够将其值传递给它的祖父p。 我想要定义值的子组件:
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/>
);
});
GrandParent Comp:
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)}/>
);
});
这可能吗?
答案 0 :(得分:4)
您似乎只需要一个将流向Grandfather
组件的事件。在React中,props
向下流动,events
向上流动。因此,下面的代码通过onSelect
将Grandfather
事件发送到Parent
:
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)} />
);
});
答案 1 :(得分:-1)
声明/初始化Grandfather
组件中的变量,并通过道具将其传递给Child
。
这是演示/容器组件的重点。如果您的Child
组件依赖于Grandfather
组件,那就是您的州应居住的地方。