首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >访问子组件中在父组件中定义的变量

访问子组件中在父组件中定义的变量
EN

Stack Overflow用户
提问于 2020-01-29 20:59:28
回答 1查看 210关注 0票数 0

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

代码语言:javascript
复制
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>
EN

回答 1

Stack Overflow用户

发布于 2020-01-29 21:02:53

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

代码语言:javascript
复制
const ChildComponent = (props) => {

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

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

   return (
      <ChildComponent someVariable={someVariable} />
   )
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59967681

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档