【发布时间】:2020-11-03 17:32:52
【问题描述】:
假设您正在使用containment,但突然之间您需要中间组件与它包含的子组件进行交互。
他们在反应文档中说:
如果孩子需要在渲染之前与父母沟通,您可以使用渲染道具更进一步。
这是我的情况,我需要Top 和Intermediate 组件来控制Bottom 组件的(不同)道具。
知道Top 包含Intermediate 组件,其中包含Bottom 组件(html 层次结构)。
这里有一些东西可以玩(按下按钮): https://stackblitz.com/edit/react-props-not-rendering-issue?file=src/App.js
打字稿中的等效项:
import React, {useState} from 'react';
export function Top() {
const [a, sA] = useState(false);
function renderBottom(b: boolean) {
return (
<Bottom a={a} b={b}/>
);
}
return (
<div>
<div>A in TOP: {a ? 'true' : 'false'}</div>
<button onClick={e => sA(!a)}>A</button>
<Intermediate renderBottom={renderBottom}/>
</div>
);
}
export function Intermediate(p: {renderBottom: any}) {
const [b, sB] = useState(false);
const BottomComponentWithASet = p.renderBottom;
return (
<div style={{background: 'red'}}>
<div>B in Intermediate: {b ? 'true' : 'false'}</div>
<button onClick={e => sB(!b)}>B</button>
<BottomComponentWithASet b={b}/>
</div>
);
}
export function Bottom(p: {a: boolean; b: boolean; }) {
console.log(p.b); // is correct, start false, change to true on click
return (
<div>
<div>A: {p.a ? 'true' : 'false'}</div>
{/* this one bellow will alway stay true */}
<div>B: {p.b ? 'true' : 'false'}</div>
</div>
);
}
我知道我可以将b 和a 的状态处理到Top 组件中。我已经开始这样做了,但这迫使我将大量代码放入与Intermediate 组件相关的Top 组件中。
这是我以前一直在使用的,它有效。但是,它在Top 组件中添加了很多代码,这与Intermediate 组件相关(这里的示例只是一个简单的表示)。
import React, {useState} from 'react';
export function Top() {
const [a, sA] = useState(false);
// oh no, we are handling something that is related to `Intermediate` and `Bottom` component only !
const [b, sB] = useState(false);
return (
<div>
<div>A in TOP: {a ? 'true' : 'false'}</div>
<button onClick={e => sA(!a)}>A</button>
<Intermediate>
<div>B in Intermediate: {b ? 'true' : 'false'}</div>
<button onClick={e => sB(!b)}>B</button>
<Bottom a={a} b={b}/>
</Intermediate>
</div>
);
}
export function Intermediate(p: any) {
return (
<div style={{background: 'red'}}>
{ p.children }
</div>
);
}
export function Bottom(p: {a: boolean; b: boolean; }) {
console.log(p.b);
return (
<div>
<div>A: {p.a ? 'true' : 'false'}</div>
<div>B: {p.b ? 'true' : 'false'}</div>
</div>
);
}
【问题讨论】:
标签: reactjs react-state-management