【问题标题】:Make component a property so that I can access its methods使组件成为一个属性,以便我可以访问它的方法
【发布时间】: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


【解决方案1】:

这是“反应方式”:

class Foo extends React.Component<{}, {}> {
    private bar: Bar;

    render() {
        return <div><Bar ref={ el => this.bar = el } /></div>
    }
}

class Bar extends React.Component<{}, {}> {
    render() {
        ...
    }
}

更多关于参考:Refs and the DOM

【讨论】:

  • 非常感谢!这正是我想要的。
  • 组件(不是容器)是否应该从其容器中获得可引用的参数?它会与无状态保持一致,但它似乎是错误的。
  • 我不确定我是否理解您的问题。您将什么定义为容器? “可引用的参数”是什么意思?
猜你喜欢
  • 2015-12-17
  • 2017-09-04
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多