【发布时间】:2019-10-08 13:50:25
【问题描述】:
我们有:
1) 两个演示组件 - PresentationOne、PresentationTwo。并且不可能使用样式来实现它们的效果。
2) 在底层使用状态(类或 useState)的组件 - ComponentWithState。它可以是来自任何库的组件。例如,某种下拉列表。因此,我们不能使用上下文或从外部传递状态。
3) 更改表示类的按钮 - ToggleButton。
export const PresentationOne = props => {
return <div>{props.children}</div>;
};
export const PresentationTwo = props => {
return <div>{props.children}</div>;
};
export const ComponentWithState = props => {
const [state, setState] = useState(Math.random());
return state;
};
export const ToggleButton = props => {
return <div onClick={props.toggleEffect}></div>;
};
const App = () => {
const [applyEffect, setApplyEffect] = useState(false);
const toggleEffect = () => {
setApplyEffect(!applyEffect);
};
return (
<div className="App">
{applyEffect ? (
<PresentationOne>
<ComponentWithState />
</PresentationOne>
) : (
<PresentationTwo>
<ComponentWithState />
</PresentationTwo>
)}
<ToggleButton toggleEffect={toggleEffect} />
</div>
);
};
ComponentWithState 将在每次单击按钮后重新渲染为新的状态。是否有可能让这个架构工作?是否有可能告诉 React 它是同一个组件,就像我们可以在列表中使用 key prop 一样?
带有测试套件的 Git 存储库:https://github.com/vitramir/test-react-hierarchy
【问题讨论】:
标签: reactjs react-native