Javascript 在父组件中定义的子组件中的Access变量

Javascript 在父组件中定义的子组件中的Access变量,javascript,reactjs,Javascript,Reactjs,我想在子函数中访问父函数中定义的某个变量 import React from "react"; export default function Parent(props) { // Variable is definded const someVariable = false; return <div className="parentClass">{props.children}</div>; } Parent.Child = functi

我想在子函数中访问父函数中定义的某个变量

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>
从“React”导入React;
导出默认函数父项(道具){
//定义了变量
const someVariable=false;
返回{props.children};
}
Parent.Child=函数(道具){
//要访问父函数中定义的某个变量吗
返回someVariable&如果someVariable为true,则应呈现;
}
//以后像这样使用
//仅当someVariable为true时,才会呈现此属性

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

const ChildComponent = (props) => {

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

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

   return (
      <ChildComponent someVariable={someVariable} />
   )
}
constchildcomponent=(道具)=>{
返回(
{props.someVariable}
)
}
常量ParentComponent=()=>{
const someVariable=false;
返回(
)
}

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

const ChildComponent = (props) => {

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

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

   return (
      <ChildComponent someVariable={someVariable} />
   )
}
constchildcomponent=(道具)=>{
返回(
{props.someVariable}
)
}
常量ParentComponent=()=>{
const someVariable=false;
返回(
)
}

将其作为属性从父组件传递给子组件?将其作为
道具传递给子组件?您可以将该变量作为道具传递给子组件。如果这正是本文代码中的场景,您只需要在父组件中使用该变量,如
{someVariable&&props.children}
将其作为属性从父组件传递给子组件?将其作为
道具传递给子组件?您可以将该变量作为道具传递给子组件。如果这正是本文代码中的场景,您只需要在父组件中使用该变量,如
{someVariable&&props.children}