- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑以下示例:
function Travel(props) {
return (
<Welcome>
<Country name={props.name}></Country>
</Welcome>
)
}
function Welcome(props) {
return (
<>
<h1>Welcome to </h1>
<div>{props.children}</div>
</>
)
}
function Country(props) {
return (
<h3>{props.name}</h3>
)
}
ReactDOM.render(
<Travel name="Japan"/>,
document.getElementById('root')
);
输出欢迎来到日本。根据我的理解,Country 是 Travel 的孙子,我们能够在这两个组件之间建立通信。 那么,为什么我们说父组件只能通过 props 与其子组件进行通信?
除非我们将位于父组件返回值内的任何组件视为子组件...
所以,我的一般问题是:即使存在嵌套结构,位于组件 A 返回内的所有组件都是 A 的子组件?
function A(props){
return (
<B>
<C>
<D></D>
</C>
</B>
)
}
上面的例子中B、C、D都是A的 child ?从A的角度看,B、C、D没有区别吗?
最佳答案
从组件的角度来看,Country
是 Travel
的孙子。
这是我从 React 开发者工具中获取的结果组件树:
(当您检查时,您可以在右下角看到哪个组件是由哪个组件渲染的)
Travel/
├── Welcome/ -- rendered by Travel
├──├── h1 -- rendered by Welcome, Travel
├──├── div/ -- rendered by Welcome, Travel
├──├──├── Country/ -- rendered by Travel
├──├──├──├── h3 -- rendered by Country, Travel
你也可以想象有“递归树”。在此递归树中,Country
是 Travel
的子级。
Travel
组件不返回单个节点,而是返回子树。
应该看起来像这样:
{
"type": "Welcome",
"props": {
"children":[{
"type": "Country",
"props": {
"name": "Japan"
}
}]
}
}
要创建这样的子树,它首先渲染Country
。
编辑:
您提到那么,为什么我们说父级只能通过 props 与其子级进行通信?
Welcome
是 Travel
的唯一子级。您基本上是在渲染新的 React 组件(称为 Country
)并将其作为 props 传递。然后它会深入到组件树中,直到找到它的父级。所以你们是通过 Prop 进行交流的。请参阅https://reactjs.org/docs/jsx-in-depth.html
下面的丑陋代码并不真正等同于 jsx 版本,但它很好地解释了情况。
function Travel(props) {
const country = React.createElement(
"Country",
{name: props.name},
[]
);
return React.createElement(
"Welcome",
{},
[country]
);
}
关于reactjs - react : Is any descendant component a child component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58881384/
我是一名优秀的程序员,十分优秀!