【问题标题】:How to access elements rendered in another React component?如何访问在另一个 React 组件中呈现的元素?
【发布时间】:2015-07-27 15:40:08
【问题描述】:

我有一个大致如下所示的应用:

class App extends React.Component {
  render(){
    var ComponentTwo = this.props.getComponentTwo();
    return (
     <div>
       <ComponentOne />
       {ComponentTwo ? <ComponentTwo /> : []}
     </div>
    );
  }
}

ComponentTwo 并不总是同一个组件类,有时它需要与 ComponentOne 交互 - 即 - 从中​​选择某些元素并将一些侦听器附加到它们。

我希望 ComponentTwo 附带此功能,因为它仅在加载 ComponentTwo 时才需要,并且带有大量代码。

允许一个组件动态扩展另一个同级组件的最佳做法是什么?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    我认为在 React 中实现这种场景的正确方法是在 ComponentTwo 中执行一些操作后更改 App 组件的状态,然后将状态更改传递给 ComponentOne:

      onComponentTwoAction: function(someValueFromAction) {
        this.setState({
            componentOneProp: someValueFromAction
        });
      }, 
      render: function(){
        var ComponentTwo = this.props.getComponentTwo();
        return (
         <div>
           <ComponentOne componentOneProp={this.state.componentOneProp}/>
           {ComponentTwo ? <ComponentTwo onAction={this.onComponentTwoAction}/> : []}
         </div>
        );
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 2019-05-10
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多