代码之家  ›  专栏  ›  技术社区  ›  Szymon Jednac

在React中将实例变量从一个子组件传递到另一个子组件

  •  2
  • Szymon Jednac  · 技术社区  · 7 年前

    我很难理解如何通过考试 组件实例变量 live example )。我的层次结构如下:

    DataView
     |> SharedScale
     |> Graph1
     |> Graph2
     |> ...
    

    我们的想法是创造一个 共享,D3轴/刻度 在里面 SharedScale 并通过 DataView render

    class SharedScale extends React.Component {    
      render() {  
        // Create a D3 scale; i.e. an external library object, which is not serializable
        this.scaleImpl = ...
    
        // Render a D3 axis using the scale implementation
        return <div>{this.scaleImpl}</div>; 
      }
    };
    

    这个 Graph 应该得到一个关于 ,并提交 D3图表 ,基于此:

    class Graph extends React.Component {
       render() {    
         //Use the scaleImpl here to render the graph body
         return (
           <div>{get(this.props, "scaleComponent.scaleImpl", "no scale implementation")}</div>
         );
       }
    }
    

    我正试图把这些结合在一起 数据视图 ,使用 React.createRef 像这样的:

    class DataView extends React.Component {   
        constructor(props) {
          super(props);
    
          this.scaleComponent = React.createRef();
        }
    
        render() {
            return(
              <div>
                <SharedScale ref={this.scaleComponent} />
                <Graph scaleComponent={this.scaleComponent.current} />                
              </div>
            );
         }
    }
    

    问题是 render() current 场是一致的 null

    我是否遗漏了什么,或者这种方法是否因为某种原因存在根本性缺陷?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Szymon Jednac    7 年前

    render 调用事件 forceUpdate 在里面 componentDidMount :

    class DataView extends React.Component {   
      ...
    
      componentDidMount() {
        this.forceUpdate();
      }
    }
    

    从…起 componentDidMount 参考页:

    这多少有些道理 equivalent 强制更新 .

    可以找到更新的实时示例 here .