学习目标:
提示:React 父子组件传值
例如:
- 半小时掌握React 父子组件传值
学习内容:
3、组件传值
(1)父子组件传值
解决方案:自定义属性
核心语法:自定义属性
、this.props-> 传递了一个变量数据
父组件:Parent.jsx
import React, {Component} from 'react';
import './Parent.css'
import Child from "../child/Child";
class MyComponent extends Component {
// 类组件状态数据,保存在state中
state = {
msgFormParent: "父亲要传递的值",
info: "父亲传递的info信息2"
}
render() {
return (
<div className="parent-container">
<h1>组件传值:父组件</h1>
<p>{this.state.msgFormParent}</p>
{/*设置自定义属性msg, 将父组件数据赋值给这个属性*/}
<Child msg={this.state.msgFormParent} info={this.state.info}/>
</div>
);
}
}
MyComponent.propTypes = {};
export default MyComponent;
父组件css:Parent.css
.parent-container {
padding: 20px;
background: orange;
color: white;
}
子组件:Child.jsx
import React, {Component} from 'react';
import './Child.css'
class Child extends Component {
render() {
// 接收父组件传递的参数
const {msg, info} = this.props
// console.log(this.props, "this.props 当前组件的所有属性")
return (
<div className="child-container">
<h2>子组件</h2>
<p>来自父组件的数据:{msg}</p>
<p>来自父组件的信息:{info}</p>
</div>
);
}
}
export default Child;
子组件css:Child.css
.child-container {
background: #61dafb;
color: white;
}
在App.js中引入父组件:App.js
import './App.css';
// 引入页面组件
import Brand from "./views/brand/Brand";
import Parent from "./views/parent/Parent";
function App() {
return (
<div className="App">
{/*使用页面组件*/}
<Brand/>
<Parent/>
</div>
);
}
export default App;