reactjs - 如何将变量传递给道具中收到的组件?
问题描述
在 Layout.jsx 中,我有以下结构,其中 children 是一个组件。
如何将“名称”传递给“孩子”组件?
const Home = () => {
return <h1>Hello world!</h1>; {/* here I need the name */}
};
class App extends Component {
render() {
return (
<Layout>
<Switch>
<Route path='/' component={Home}/>
...
</Switch>
</Layout>
);
}
}
class Layout extends Component {
name = "John";
render() {
const { children } = this.props;
return (
<div>
{ children }
</div>
);
}
}
解决方案
React 组件必须是大写的。如果child
变量包含一个 React 组件,您可以将其存储在某个大写变量中,然后作为标签呈现。
const { child: Child } = this.props;
return (
<div>
<Child name={this.name} />
</div>
);
推荐阅读
- java - 在非 Spring Boot 应用程序中集成 Keycloak Spring Security Adapter - 重定向过多问题
- python - HackerRank 上的 SherlockAndAnagrams 算法解释错了吗?
- java - 如何制作可以接受不同多维数组的方法?
- javascript - 是否有多个 if else 问题的更简单方法?
- ios - UITableView 直到 viewDidAppear 才会呈现
- reactjs - Babel:无法让“@babel/plugin-transform-destructuring”插件工作
- regex - 正则表达式删除第 5 个逗号之前和第 6 个逗号之后的文本
- r - 将一列分类变量添加到数据框中
- c++ - 为什么 std::variant 用开始和结束迭代器编译?
- sql - Postgres 按空字符串问题分组以在输出中包含空字符串