【发布时间】:2019-05-14 00:42:45
【问题描述】:
我正在创建一个 HOC,它将在某个道具上检查其孩子(和他们的孩子),在本例中为 onEditable。如果没有指定,则假定要显示孩子,如果设置为hide,则不会呈现孩子。
(该道具不是布尔值,因为稍后我会添加更多选项)
const MyComponent = ({ children, }) => {
const getChildren = (myChildren, onEditable = 'show') => React.Children.map(myChildren, (child) => {
let myOnEditable = onEditable;
const { props, } = child;
if (props) {
const { onEditable: onEdit, children: grandChildren, } = props;
onEdit && (myOnEditable = onEdit);
typeof grandChildren === 'object'
&& getChildren(grandChildren, myOnEditable);
}
console.log(myOnEditable);
if (myOnEditable === 'show') {
return child;
}
});
return <div>{getChildren(children)}</div>;
};
ReactDOM.render(
<MyComponent>
<p onEditable="show">show</p>
Unspecified
<div onEditable="hide">
<span onEditable="show">show inside hide</span>
<p>Unspecified in hide</p>
</div>
<div onEditable="show">
<span onEditable="hide">hide inside show</span>
<p>Unspecified in show</p>
</div>
</MyComponent>,
document.getElementById('root')
);
<div id='root'/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
以级联方式分配正确的onEditable 值是可行的,正如在控制台中看到的那样,但仅渲染show 则不行。遵循代码时哪种有意义。问题是;我不知道如何解决。
对我来说最难理解的事情是能够渲染一个父组件,它的onEditable 设置为hide,而它的一个子组件设置为show。
这可能听起来令人困惑,所以我会解释更多。 onEditable 设置为 hide 的父组件将此属性级联到它的子级(以我想要我的 HOC 的方式),但如果孩子或孙子有这个道具设置显示,他所有的父母都需要渲染也是,但不是他的兄弟姐妹(因为他们仍然拥有父母的 hide 属性,除非另有说明)
所以我希望在我的示例中使用以下 DOM 结构:
<p onEditable="show">show</p>
Unspecified
<div onEditable="hide">
<span onEditable="show">show inside hide</span>
</div>
<div onEditable="show">
<p>Unspecified in show</p>
</div>
【问题讨论】:
标签: javascript reactjs ecmascript-6