我想知道是否可以根据需要获取组件实例。
我将新组件作为子组件置于主状态,但在两个文件中都没有相同的对象。
我需要在MainComponent中达到子状态。在Google中寻找componenet实例并没有帮助,也许我已经失去了重点,而这个名称却有所不同。
这是我的主要组件:
import React, { Component } from 'react';
import AnotherComponent from './../whatever/AnotherComponent';
class MainComponent extends Component {
constructor(props) {
super(props);
this.state = {
children: [],
};
}
addChild() {
const { children } = this.state;
this.setState({
children: children.push(<AnotherComponent />)
});
}
getChildrenState(component) {
return component.state(); // this doesn't work!
}
render() {
const { children } = this.state;
return (
<div>
{(children.map(i => (<div key={this.getChildrenState(i).id}>{i}</div>))}
</div>
)
}
这是AnotherComponent
import React, { Component } from 'react';
class AnotherComponent extends Component {
constructor(props) {
super(props);
this.state = {
id: 144,
};
}
render() {
return (
<div>
Here it is my cHild!
</div>
)
}
答案 0 :(得分:1)
如果要访问子组件的状态(此处为AnotherComponent
),则可以:
AnotherComponent
内,并将其值传递给更改侦听器的父级(这里为MainComponent
)(每当状态更改时);或者; MainComponent
)中保持状态,并将该值作为prop传递给子级。如果您要我提供示例实现,请告诉我。
答案 1 :(得分:1)
将<AnotherComponent/>
置于状态是没有意义的,因为它是与特定组件实例无关的React元素对象。
访问父组件中的子状态会破坏封装并指示设计问题。
应该使用ref来检索类组件的实例,这样做是为了访问实例state
,这是扩展不提供所需功能的第三方组件的最后一招。
如果AnotherComponent
是第一方组件,则应进行相应设计,以免从外部访问state
:
render() {
return (
<div key={this.state.id}>{this.state.id}</div>
)
}
如果输出需要更灵活,则可以使用render prop模式:
render() {
const render = React.Children.only(children);
return (
<div key={this.state.id}>{render(this.state.id)}</div>
)
}
并按如下方式使用:
<AnotherComponent>{id => <div>{id}</div>}</AnotherComponent>