【问题标题】:React: How can you access the class name of a parent component from a child without passing it down as props?React:如何从子组件访问父组件的类名而不将其作为道具传递?
【发布时间】:2018-06-03 17:00:16
【问题描述】:

假设你有一个父组件:

// ParentComponent

class ParentComponent extends React.Component {

  render() {
    return(
      <ChildComponent/>
    )
  }
}

有没有办法从子组件内部访问父组件的类名而不将其作为 props 传递?

// ChildComponent

class ChildComponent extends React.Component {

  // ?????
  getParentComponentName() {
    return this.???  // Should return "ParentComponent"
  }

  render() {
    return(
      <div/>
    )
  }
}

我希望能够在不将其作为道具传递的情况下访问它。谢谢!

【问题讨论】:

  • 事件如果可以不作为道具传递,你不应该这样做
  • 为什么不用静态,我的意思是你可以在父组件中创建一个静态函数并在子组件中使用它。
  • 你能在这里分享用例吗?

标签: reactjs


【解决方案1】:

你需要访问ReactInternalFiber点赞

class Child extends React.Component {
    constructor(props) {
        super(props);
        this.state = { name: '' }
    }
    getParentName = () =>{
        this.setState({ name: this._reactInternalFiber._debugOwner.type.name })
    }
    render() {
        return (
            <div>
                <h1>Name: {this.state.name}</h1>
                <button onClick={this.getParentName}>Get Parent Name</button>
            </div>
        )
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-04
    • 2020-07-30
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 2021-05-26
    • 2020-08-25
    相关资源
    最近更新 更多