react 点击事件+父子传值

接下来要做的效果是,在父组件添加两个按钮,点击后改变父组件传过去的值

父组件

 1 import React,{ Component } from ‘react‘;
 2 import Test from ‘./component/test‘;
 3 //声明welcome组件
 4 class welcome extends Component {
 5   //声明一个构造函数
 6   constructor(props) {
 7     super(props);
 8     //this.state是定义组件状态,可理解为组件中的数据,好比Vue中的data
 9     this.state = {
10       userName: ‘路飞‘,11       userAge: 19
12     }
13   }
14   changUserName(){
15     //要修改this.state中的值,这是唯一的方法
16     this.setState({
17       userName: ‘路飞:海贼王的男人‘
18     })
19   }
20   // react元素 一律写在render函数中
21   render() {
22     return (
23       <div>
24         {/* 在子组件中声明一个userName属性,将this.state.userName的值传递到子组件中 */}
25         <Test userName={this.state.userName} userAge={this.state.userAge}></Test>
26         {/* 声明一个点击事件后面跟着一个bind(this) 是为了解决this指向问题 ,改变this指向 */}
27         <button onClick={this.changUserName.bind(this)}>改变userName</button>
28       </div>
29     );
30   }
31 }
32 //最后一定要记住 向外输出
33 export default welcome;

子组件

 1 import React,{ Component } from ‘react‘;
 2 
 3 class test extends Component {
 4   render() {
 5     return (
 6       <div>
 7         <h1>海贼王</h1>
 8         {/* 在子组件中用this.props接收父组件中传递过来的值 */}
 9         {[this.props.userName,this.props.userAge]}
10 
11         {console.log(this.props)}
12         {/* 通过控制台打印,this.props是传递过来的是一个对象:{userName: "路飞",userAge: 19} */}
13       </div>
14     );
15   }
16 }
17 
18 export default test;

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...