【问题标题】:Can we access to a react child from a custom composition?我们可以从自定义组合中访问 react 子节点吗?
【发布时间】:2018-03-30 11:53:20
【问题描述】:

在 ReactJS 树中可以走多深?假设我们有:

function SplitPane(props) {
    return (
        <OtherCompo>
            { props.left }
        </OtherCompo>
    );
}

function App() {
    return (
        <SplitPane
            left={ <Contacts /> } />
    );
}

如果我们想从 App 组件到最后一个子组件(并修改 props),我们可以使用 children.map 等。但据我了解,我们只能到 SplitPane 组件。 因为props.childrenSplitPane 没有定义,所以我们将无法深入树中。但是,SplitPane 有一些孩子。那么有没有办法从App 组件访问这些孩子?

【问题讨论】:

    标签: reactjs children


    【解决方案1】:

    如果您想从App 组件修改深层子组件,您可以将方法从父组件传播到所有子组件,直到您到达需要修改的相关子组件。或者,更好的方法是使用ReactJS Context

    使用上下文方法,您从App 组件内部声明子组件的上下文,这将允许最终子组件直接调用声明的上下文,而中间组件不会干扰信息的传播。

    您的代码将如下所示:

    class OtherCompo extends React.Component {
        static contextTypes = {
            left: React.PropTypes.instanceOf(React.Component)
        };
    
        render() {
            return (
                <div>
                    <SomeComp />
                    { this.context.left }
                    <SomeOtherComp />
                </div>
            );
        }
    }
    
    class SplitPane extends React.Component {
        render() {
            return (
                <OtherCompo></OtherCompo>
            );
        }
    }
    
    class App extends React.Component {
        static childContextTypes = {
            left: React.PropTypes.instanceOf(React.Component)
        };
    
        getChildContext() {
            return { left: <Contacts /> };
        }
    
        render() {
            return (
                <SplitPane />
            );
        }
    }
    

    【讨论】:

    • 很有趣,但If you want your application to be stable, don’t use context. It is an experimental API and it is likely to break in future releases of React. 看起来很吓人。
    • 我不会太担心,只要您决定更新 ReactJS 的版本,您只需验证它是否仍然有效,无论如何,您可以从如果您决定不使用上下文,则为父级,这将始终有效。
    猜你喜欢
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2023-03-03
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多