[英]How do I pass props to child without the use of modules?
目標:從父級組件向子級發送屬性並進行渲染。
問題:
import ChildComponent from 'someLocation';
注意:
例:
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')
);
<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.