反应大师的快速问题;)
React.Children.only是它的顶级api之一,并且很常被react-redux(< Provider />)和React Router(< Router />)用来注入商店/路由器作为上下文,背后的原因是什么这,为什么不简单地返回props.children?似乎与JSX有关?
编辑:请不要解释什么是React.Children.only,我问为什么使用它而不是props.children,这似乎更强大/灵活.
正如
docs所指出的那样
Verifies that children has only one child (a React element) and returns it. Otherwise this method throws an error.
那么现在为什么仅使用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> ); } }
可以像这样使用:
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> ) } }
希望这个对你有帮助.