【发布时间】:2017-04-02 19:26:40
【问题描述】:
目前正在创建一个 TypeScript/React 应用程序,我遇到了一个问题。我想要做的是将一个组件作为属性存储在另一个组件中,这样我就可以直接访问它的方法和属性(因为我需要访问它的子方法)。基本上我想做的是这样的:
class FooContainer extends React.component<FooContainerProps,FooContainerState> {
bar: Bar;
constructor(props: FooContainerProps) {
super(props);
this.bar = new Barcontainer({bar_prop1: asdf, ...});
}
aThing() {
this.bar.doSomething();
}
render() {
return <Foo bar={this.bar} />;
}
}
class Foo extends React.component<FooProps,undefined> {
render() {
return ( ... {this.props.bar} ...);
}
}
class BarContainer extends React.component<BarContainerProps,BarcontainerState>{
doSomething() {
}
render() {
return <div>...</div>;
}
每当我设置 foo 的状态时,我还需要更新 bar,因为 bar 的 props 依赖于 foo 的状态。有什么想法吗?
编辑:非常感谢您的帮助。使用给定的内容,我找到了一种方法,使组件不会有任何对象属性,所以它现在看起来像这样:
class FooContainer extends React.component<FooContainerProps,FooContainerState> {
bar: Bar;
registerBar(bar: Bar) {
this.bar = Bar;
}
aThing() {
this.bar.doSomething();
}
render() {
return <Foo
registerBar={this.registerBar.bind(this)}
bar={this.bar} />;
}
}
class Foo extends React.component<FooProps,undefined> {
render() {
return (
...
<Bar ref={(el) => {this.props.registerBar(el)}} />
...
);
}
}
class BarContainer extends React.component<BarContainerProps,BarcontainerState>{
doSomething() {
}
render() {
return <div>...</div>;
}
再次感谢您的帮助!
【问题讨论】:
-
Foo.render方法真的只返回this.bar.render()结果吗?如果是这样,那么Foo没有理由成为反应组件。如果您的真实代码不同,请使用可以更好地解释您的场景的内容更新问题。 -
不,这只是它返回的一部分。我试图做一个最小的例子。
-
目前还不清楚您要完成什么。您不应该在道具中传递组件。道具和状态应该只包含渲染组件的数据。将
BarContainer渲染为Foo的普通子级有什么问题?也许解释一下你想要做什么? -
如果我只是将
BarContainer渲染为Foo的子级,我将如何访问FooContainer中的BarContainer的功能?这是主要问题。 -
也许
this.refs就是你要找的。span>
标签: reactjs typescript