简体   繁体   English

将 React 组件作为 prop 传递给另一个组件

[英]Pass React component as prop to another component

I am trying to pass complete parent component as props to its child component.我正在尝试将完整的父组件作为道具传递给它的子组件。 Whereas, while trying to pass some data from parent to child, I imported the child into parent.然而,在尝试将一些数据从父级传递给子级时,我将子级导入了父级。 So, how can I do that now in other way around?那么,我现在怎么能以其他方式做到这一点呢? Any suggestions?有什么建议么? As I want to re render Parent component upon some state change of child component.因为我想在子组件的某些 state 更改时重新渲染父组件。 Example Added:示例添加:

// Parent Component
import B from './B.js';

class A extends React.Component{
constructor(props, context){
        super(props, context);
         this.state = {
                 showB: false
         }
    }
onClick = () =>{
this.setState({ 
            showB: true
            });
}
render(){
return(
{
 this.state.showB ? <B /> : 
<div>
<Button onClick={this.onClick}>VIEW B </Button>
</div>
<h1>Some text</h1>
)
}
}

// Child Component

class B extends React.Component{
constructor(props, context){
        super(props, context);
         this.state = {
                 showA: false
         }
    }
onClick = () =>{
this.setState({ 
            showA: true
            });
}
render(){
return(
{
 this.state.showA ? <A /> : 
<div>
<Button onClick={this.onClick}>Back</Button>
</div>
<h1>Back to Component A</h1>
)
}

}

When you want to toggle between parent and child component, I recommend passing down the callback function from parent to child and access that function to navigate back to the parent component.当您想在父组件和子组件之间切换时,我建议将回调 function 从父组件传递给子组件并访问该 function 以导航回父组件。

Your parent component should be this,你的父组件应该是这个,

class A extends React.Component{
  constructor(props, context){
    super(props, context);
    this.state = {
      showB: false
    }
  }

  onClick = () =>{
    this.setState({ 
      showB: !this.state.showB    //This will negate the existing state
    });
  }

  render(){
    return(
      <>  //use Fragments / div here 
      {
        this.state.showB ? 
        <B click={this.onClick}/> //Provide callabck function here
        : 
        <div>
          <button onClick={this.onClick}>VIEW B </button>
          <h1>Some text</h1>
        </div>
      }
      </>
    )
  }
}

You child component should be this,你的子组件应该是这个,

class B extends React.Component{
  render(){
    return( 
      <div>
        <button onClick={this.props.click}>Back</button>
        <h1>Back to Component A</h1>
      </div>
    )
  }
}

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM