簡體   English   中英

如何在不使用模塊的情況下將道具傳遞給孩子?

[英]How do I pass props to child without the use of modules?

目標:從父級組件向子級發送屬性並進行渲染。

問題:

  1. 我無法使用模塊,例如我未使用npm,這意味着require對我不可用。 示例: import ChildComponent from 'someLocation';
  2. 父組件和子組件存在於不同的文件中。
  3. 我正在嘗試將道具從父母那里送給孩子。

注意:

  • 我處於無法理解為什么無法將道具發送到子組件的情況。
  • 我完全知道,如果將“子代”組件放入“父代”的組件文件中,則能夠將所需的道具發送給“子代”。 問題是,如果我有一個“根”>“子”>“子”>“子”>“子”情況,對我而言,將所有內容維護在一個文件中是不可行的。 否則,請隨時分享您的意見。

例:

  • 子組件,存在於src/parent/child/index.js
const Child = ({ name }) => {
    return (
        // name is undefined!
        <div>{name}, I am the child component</main>
    );
};

ReactDOM.render(
    React.createElement(Child),
    document.querySelector('#Child')
);
  • 父組件,存在於src/parent/index.js
class Parent extends React.Component {
    render() {
        const name = "Giggles";

        return (
            <div>
                <div id="Child" name={name}></div>
            </div>
        );
    );
};

ReactDOM.render(
    React.createElement(Parent),
    document.querySelector('#Parent')
);
  • index.html(偽代碼):
<html>
    <head>dependencies in here, react, react-dom and babeljs</head>
    <body>
        <div id="Parent"></div>
    </body>
    <script src="src/parent/index.js"></script>
    <script src="src/parent/child/index.js"></script>
</html>

您實際上可以將<html>標記底部的腳本順序更改為:

<html>
    <head>dependencies in here, react, react-dom and babeljs</head>
    <body>
        <div id="Parent"></div>
    </body>
    <script src="src/parent/child/index.js"></script>
    <script src="src/parent/index.js"></script>
</html>

因此,您將能夠使用Parent類訪問文件中的Child變量,因此傳遞props就像下面的代碼一樣簡單:

class Parent extends React.Component {
    render() {
        const name = "Giggles";

        return (
            <div>
                <Child name={name} />
            </div>
        );
    );
};

另外,您應該在Child所在的文件中刪除ReactDOM渲染,因此它將如下所示:

const Child = ({ name }) => {
    return (
        // name is undefined!
        <div>{name}, I am the child component</main>
    );
};

這是一個非常奇怪的限制。您說“請理解”,但我不是,所以我認為您應該解釋原因。 它可以幫助您找到更好的解決方案。

這里的問題是雙重的:

1)您的Parent組件實際上並沒有渲染您的孩子,您只有一個id為Child的div,這在React中是沒有意義的。

2)父組件所在的腳本需要以某種方式訪問​​子組件,並且如果沒有模塊捆綁器,則需要將其放在一個可以像window一樣到達的命名空間中

3)您正在渲染兩個React樹。 要將道具從一個組件傳遞到另一個組件,它們必須位於同一渲染樹中。

const Child = ({ name }) => {
    return (
        <div>{name}, I am the child component</main>
    );
};


window.Child = Child

-

const Child = window.Child

class Parent extends React.Component {
    render() {
        const name = "Giggles";

        return (
            <div>
                <Child name={name} />
            </div>
        );
    );
};

ReactDOM.render(
    React.createElement(Parent),
    document.querySelector('#Parent')
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM