首页 > 解决方案 > 访问父组件中定义的子组件中的变量

问题描述

我想在子函数中访问在父函数中定义的 someVariable。

import React from "react";

export default function Parent(props) {
    // Variable is definded
    const someVariable = false;

    return <div className="parentClass">{props.children}</div>;
}

Parent.Child = function(props) {
    // Want to access someVariable defined in parent function
    return someVariable && <div className="childClass">Should render if someVariable is true</div>;
}

// Use like this later
<Parent>
    // This will be rendered only if someVariable is true
    <Parent.Child />
</Parent>

标签: javascriptreactjs

解决方案


您可以将父组件中的变量作为道具传递给子组件:

const ChildComponent = (props) => {

    return (
       <View><Text>{props.someVariable}</Text></View>
    )
}

const ParentComponent = () => {
   const someVariable = false;

   return (
      <ChildComponent someVariable={someVariable} />
   )
}

推荐阅读