[英]How to identify React component tags after build in a CRA app?
I would like to create and use this component in React with ES6:我想用 ES6 在 React 中创建和使用这个组件:
<Menu>
<MenuHeader>Hi</MenuHeader>
<MenuItem>Hello</MenuItem>
<MenuFooter>End</MenuFooter>
</Menu>
I've defined a component to handle this structure:我已经定义了一个组件来处理这个结构:
export class Menu extends React.Component {
render() {
return (
<div ...>
<div ...>
{HOW TO SELECT HEADER?}
</div>
<div ...>
{HOW TO SELECT ITEM?}
</div>
<div ...>
{HOW TO SELECT FOOTER?}
</div>
</div>
)}
} }
It's okay to iterate over children and select by type.name
while running on the dev server without transpilation:在没有转译的开发服务器上运行时,可以通过
type.name
遍历 children 和 select:
{ React.Children.map(this.props.children, child => { return child.props.type === 'MenuItem' ? <>{ child }</> : '' } ) }
But it does not work after building it (cause of uglify/minify process).但它在构建后不起作用(导致 uglify/minify 过程)。
For example, Semantic UI React handles it well - but it uses interfaces and written in TypeScript so I cannot use it as reference.例如,Semantic UI React 处理得很好——但它使用接口并用 TypeScript 编写,所以我不能将其用作参考。
And one more thing (ah Steve:): I do not want to use npm eject
.还有一件事(啊史蒂夫:):我不想使用
npm eject
。
This is normally done by allowing the compound components inside them to render their own children and Menu
would just render the children
it gets, hence maintaining the order.这通常是通过允许其中的复合组件渲染它们自己的子组件来完成的,而
Menu
只会渲染它获得的children
组件,从而保持顺序。
You might want to share the state of things happening between the Header, Body and Footer, so we add a ContextProvider to the Menu component, so they can all share common state.您可能希望共享 Header、Body 和 Footer 之间发生的事情的 state,因此我们将 ContextProvider 添加到 Menu 组件,因此它们都可以共享公共 Z9ED39E2EA931586B6A985A6942EF573E
const rootEl = document.getElementById('root'); const { render } = ReactDOM; const { createContext } = React; function MenuHeader({ children }) { return ( <header className="menu-header"> {children} </header> ) } function MenuBody({ children }) { return ( <div className="menu-body"> {children} </div> ) } const MenuContext = createContext(); Menu.Header = MenuHeader; Menu.Body = MenuBody; function Menu({ children }) { return ( <MenuContext.Provider value={null}> <div className="menu-wrapper"> {children} </div> </MenuContext.Provider> ); } function App() { return ( <Menu> <Menu.Header>Menu Header</Menu.Header> <Menu.Body>Menu Body</Menu.Body> </Menu> ); } render(<App />, rootEl);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root" />
Another common technique used by Frameworks like Ant.Design is to map over the children and add common props to them (although context would be the better solution in my opinion)像 Ant.Design 这样的框架使用的另一种常用技术是 map 覆盖孩子并向他们添加常用道具(尽管我认为上下文是更好的解决方案)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.