AGE*_*AGE 1 javascript reactjs
目标:从父组件向子组件发送属性并进行渲染.
问题:
import ChildComponent from 'someLocation';注意:
例:
src/parent/child/index.jsconst 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.jsclass 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)
<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)