反应:子代组件是子组件吗?

时间:2019-11-15 16:47:02

标签: reactjs

考虑以下示例:

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')
);

会输出欢迎来到日本。据我了解,国家/地区旅行的孙代,我们能够在这两个部分之间建立联系。 So, why are we saying Parent can only communicate with its children through props?除非我们将父组件的返回内的任何组件视为子组件,否则...

所以,我的通用问题是:即使存在嵌套结构,位于组件A的返回内部的所有组件都是A的子代

function A(props){
  return (
   <B>
     <C>
       <D></D>
     </C> 
   </B>
  )
}

在上面的示例B中,C和D都是A的子代吗?从A的角度来看,B,C和D之间没有区别吗?

4 个答案:

答案 0 :(得分:2)

从组件的角度来看,CountryTravel的曾孙。

这是我从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

您也可以想象有“递归树”。在此递归树中,CountryTravel的子代。

Travel组件不会返回单个节点,但会返回子树。

应该看起来像这样:

{
  "type": "Welcome",
  "props": {
    "children":[{
      "type": "Country",
      "props": {
        "name": "Japan"
      }
    }]
  }
}

要创建这样的子树,它首先渲染Country

编辑:

您提到了So, why are we saying Parent can only communicate with its children through props?

WelcomeTravel的独生子。您基本上是在渲染新的react组件(称为Country)并将其作为道具传递。然后将其传递到组件树中,直到找到其父级为止。因此,您通过道具进行交流。参见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]
  );
}

答案 1 :(得分:0)

由于从// index.js app.get('/data', require('./mymiddleware.js')) // mymiddleware.js module.exports = function (req, res) { console.log("request.app = " + JSON.stringify(req.app)); res.json("get data"); } 访问了Country,因此我想说它是Travel的子代。它恰好位于布局中的其他组件内部,但是该组件(Travel)并未以任何方式与其交互。现在,如果您在Welcome中有Country,那么它将是Welcome.render的子代和Welcome的孙子。

答案 2 :(得分:0)

CountryTravel的子代,因为您只是在传递道具时不进行道具钻孔。

如果您将名称传递给Welcome,然后在内部将其传递给Country,那么它将是“孙子”。

将其视为不是DOM节点继承,而是组件props范围。并且您将看到WelcomeCountry都是Travel的子代。

答案 3 :(得分:0)

通用答案为否。从A的角度来看,B,C和D之间存在差异

让我们看看下面的示例。

// Passing the props {data:"From one"}
export function One(props) {
console.log(props);
  return (
    <React.Fragment>
      one
      <Two>
        <Three></Three>
      </Two>
    </React.Fragment>
  );
}

function Two(props) {
  console.log(props);
  return <React.Fragment>Two {props.children} </React.Fragment>;
}

function Three(props) {
  console.log(props);
  return "Three";
}

与您提到的结构类似。 正如您从下面的输出中看到的那样-道具没有传递给孙子Three

日志依次为One TwoThree的道具。 enter image description here

相关问题