
正文
react 父组件 向 子组件 传值
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
父组件
import React, { Component } from 'react';
import Test from './component/test';
//声明welcome组件
class welcome extends Component {
//声明一个构造函数
constructor(props) {
super(props);
//this.state是定义组件状态,可理解为组件中的数据,好比Vue中的data
this.state = {
userName: '路飞',
userAge: 19
}
}
// react元素 一律写在render函数中
render() {
return (
<div>
<h1>welcome to the world of react</h1>
{/* 在子组件中声明一个userName属性,将this.state.userName的值传递到子组件中 */}
<Test userName={this.state.userName} userAge={this.state.userAge}></Test>
</div>
);
}
}
//最后一定要记住 向外输出
export default welcome;
子组件
import React, { Component } from 'react'; class test extends Component {
render() {
return (
<div>
<h1>我是test组件</h1>
{/* 在子组件中用this.props接收父组件中传递过来的值 */}
{[this.props.userName, this.props.userAge]} {console.log(this.props)}
{/* 通过控制台打印,this.props是传递过来的是一个对象:{userName: "路飞", userAge: 19} */}
</div>
);
}
} export default test;







![【电子书】[职业技术] 《深入react技术栈》[陈屹][epub+mobi+azw3] 【电子书】[职业技术] 《深入react技术栈》[陈屹][epub+mobi+azw3]](https://www.04ip.com/template/qe/style/noimg/4.jpg)
