Xle*_*lee 17 children reactjs react-router react-redux
反应大师的快速问题;)
React.Children.only是它的顶级api之一,并且通常被react-redux(<Provider />
)和React Router(<Router />
)用来注入商店/路由器作为上下文,这背后的原因是什么,为什么不简单return props.children
呢?似乎与JSX有关?
编辑:请不要解释什么是React.Children.only,我问为什么使用它而不是props.children,这似乎更强大/灵活.
Kar*_*yan 13
正如文档中所指出的那样
验证子项只有一个子项(React元素)并返回它.否则此方法会抛出错误.
那么现在为什么仅仅使用它有用props.children
呢?
主要原因是它抛出一个错误,因此停止整个开发环境,所以你不能跳过它.
这是一个方便的工具,它创建了一个特定的层,强制执行这个只有一个孩子的特定规则.
当然你可以使用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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
可以像这样使用:
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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
希望这个对你有帮助.
归档时间: |
|
查看次数: |
9148 次 |
最近记录: |