如何在不使用模块的情况下将道具传递给孩子?

AGE*_*AGE 1 javascript reactjs

目标:从父组件向子组件发送属性并进行渲染.

问题:

  1. 我无法使用模块,例如我没有使用npm,这意味着我无法使用require.例:import ChildComponent from 'someLocation';
  2. 父组件和子组件存在于不同的文件中.
  3. 我正在尝试从父母向孩子发送道具.

注意:

  • 我处于这样一种情况,我不明白为什么我无法向子组件发送道具.
  • 我完全清楚,如果我将Child组件放在Parent的组件文件中,我可以将我需要的道具发送给Child.问题是,如果我有Root> Child> Child> Child> Child情况,那么将所有内容保存在一个文件中对我来说是不可行的.请随意分享您的意见.

例:

  • 子组件,存在于 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')
);
Run Code Online (Sandbox Code Playgroud)
  • 父组件,存在于 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')
);
Run Code Online (Sandbox Code Playgroud)
  • 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>
Run Code Online (Sandbox Code Playgroud)

小智 8

您实际上可以将<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>
Run Code Online (Sandbox Code Playgroud)

因此,您将能够Child使用Parent类访问文件中的变量,因此传递道具就像下面的代码一样简单:

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

        return (
            <div>
                <Child name={name} />
            </div>
        );
    );
};
Run Code Online (Sandbox Code Playgroud)

此外,您应该删除Child所在文件中的ReactDOM渲染,因此它将如下所示:

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