向反应专家提出快速问题;)
React.Children.only https://reactjs.org/docs/react-api.html#reactchildrenonly是它的顶级 api 之一,react-redux 非常常用(<Provider />
) 和 React 路由器 (<Router />
)将存储/路由器注入作为上下文,这背后的原因是什么,为什么不简单地return props.children
?似乎与 JSX 有关?
编辑:请不要解释what是 React.Children.only,我要求why使用它代替 props.children,这似乎更强大/灵活。
正如中指出的docs https://reactjs.org/docs/react-api.html#reactchildrenonly
验证孩子只有一个孩子(一个React元素)并返回它。否则该方法会抛出错误。
那么现在为什么它比仅仅使用更有帮助props.children
?
主要原因是它抛出一个错误,从而停止整个开发流程,所以你不能跳过它。
这是一个方便的实用程序,它强制执行具有特定和only一个小孩。
当然,你可以使用propTypes
,但这只会在控制台中发出警告,您可能会错过它。
一个用例React.Children.only
可以是强制执行应由一个逻辑子组件组成的特定声明性接口:
class GraphEditorEditor extends React.Component {
componentDidMount() {
this.props.editor.makeEditable();
// and all other editor specific logic
}
render() {
return null;
}
}
class GraphEditorPreview extends React.Component {
componentDidMount() {
this.props.editor.makePreviewable();
// and all other preview specific logic
}
render() {
return null;
}
}
class GraphEditor extends React.Component {
static Editor = GraphEditorEditor;
static Preview = GraphEditorPreview;
wrapperRef = React.createRef();
state = {
editorInitialized: false
}
componentDidMount() {
// instantiate base graph to work with in logical children components
this.editor = SomeService.createEditorInstance(this.props.config);
this.editor.insertSelfInto(this.wrapperRef.current);
this.setState({ editorInitialized: true });
}
render() {
return (
<div ref={this.wrapperRef}>
{this.editorInitialized ?
React.Children.only(
React.cloneElement(
this.props.children,
{ editor: this.editor }
)
) : null
}
</div>
);
}
}
可以这样使用:
class ParentContainer extends React.Component {
render() {
return (
<GraphEditor config={{some: "config"}}>
<GraphEditor.Editor> //<-- EDITOR mode
</GraphEditor>
)
}
}
// OR
class ParentContainer extends React.Component {
render() {
return (
<GraphEditor config={{some: "config"}}>
<GraphEditor.Preview> //<-- Preview mode
</GraphEditor>
)
}
}
希望这有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)