javascript - 访问父组件中定义的子组件中的变量
问题描述
我想在子函数中访问在父函数中定义的 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>
解决方案
您可以将父组件中的变量作为道具传递给子组件:
const ChildComponent = (props) => {
return (
<View><Text>{props.someVariable}</Text></View>
)
}
const ParentComponent = () => {
const someVariable = false;
return (
<ChildComponent someVariable={someVariable} />
)
}
推荐阅读
- r - 如何解决`sf`安装错误:在标准或给定位置找不到proj_api.h
- python - 解开 Exception 的子类时 Pickle 失败
- python - 使用 Selenium 抓取延迟加载网站
- sql-server - TSQL,维表的重构
- python - 打印 Mbox 消息时出现 UnicodeEncodeError
- matlab - 传递给 fitgmdist 的有效起始条件是什么?
- c - 绑定:尝试将 AF_INET6 绑定到 INADDR_ANY(到 localhost)时参数无效
- azure - ADF 表达式生成器,所有字符串字段大写
- java - 根据名称和来源将列出的对象分组为java中的键
- angular - 我不知道为什么它显示这些错误