首页 > 解决方案 > 将 React 组件作为 prop 传递给另一个组件

问题描述

我正在尝试将完整的父组件作为道具传递给它的子组件。然而,在尝试将一些数据从父级传递给子级时,我将子级导入了父级。那么,我现在怎么能以其他方式做到这一点呢?有什么建议么?因为我想在子组件的某些状态更改时重新渲染父组件。示例添加:

// 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>
)
}

}

标签: javascriptreactjs

解决方案


当您想在父组件和子组件之间切换时,我建议将回调函数从父组件传递给子组件并访问该函数以导航回父组件。

你的父组件应该是这个,

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>
      }
      </>
    )
  }
}

你的子组件应该是这个,

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

演示


推荐阅读