javascript - 将 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>
)
}
}
解决方案
当您想在父组件和子组件之间切换时,我建议将回调函数从父组件传递给子组件并访问该函数以导航回父组件。
你的父组件应该是这个,
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>
)
}
}
推荐阅读
- reactjs - 在 redux 中进行循环调度是否正确?
- java - 如何在 Jmeter 中传递仅适用于工作日的日期(yyyy-MM-dd)
- python - 无法使按钮在 Tkinter 中正常工作
- wordpress - 添加订单时出现 Wocomerce API 内部服务器错误
- python - 通过比较行来过滤 pandas pandas 数据框
- javascript - 当 Com1 和 Com2 是兄弟姐妹时,如果触发功能,类型“parentCom”上不存在属性“childCom1”
- r - 在 gsub r 中使用正则表达式模式
- docker - 如何在 terraform 0.14 中选择正确的 docker 提供程序
- javascript - 如何在 React 中显示 json 数据的特定键
- f# - 我可以在 F# 中对选项检查进行分组吗