父组件给子组件传递参数问题及参数传值问题

来源:2-5 自由编程

weixin_慕码人9177259

2020-03-30 12:58:40

父组件Counter.js

import React,{Component,Fragment} from 'react';

import Child from './Child';

class Counter extends  Component{

constructor(props) {

     super(props);

this.state={

inputValue:'点击,数字+2',

value:1

}

this.handleClick=this.handleClick.bind(this);

//给handleClick函数绑定this,函数里的this永远指向Counter

}

handleClick(){

const value=this.state.value+2;//实现数字加2

//state是改变数据的

this.setState({

value:value

})

}

 

render(){

return(

<Fragment>

<button onClick={this.handleClick}>{this.state.inputValue}</button>

<Child

  count={this.state.value}

/>

</Fragment>

)

}

}

export default Counter;

子组件Child.js

import React ,{Component}from 'react';

// React是react模块中默认组件命名

// {Component}引入react文件中的成员组件Component,

//Const Component = React.Component

class Child extends Component{

constructor(props) {

    super(props);

}

render(){

//this.props=this.state{ inputValue:'点击,数字+2', value:1}

//count={this.state.value}

var count=this.props.count;

return(

<p>{count}</p>

)

}

}

export default Child;

请问这里父组件给子组件传值,父组件中

<Child  count={this.state.value} />

子组件中var count=this.props.count;

通过父组件state和子组件props是否能这样理解:

我疑惑的点有三个:

1,props是不是和super(props)继承构造方法有关,还是和父组件有关呢?

2,子组件中this.props,count=this.props.count 是this.prop也有个count属性吗?为什么呢?

请大神指导



写回答

1回答

_是你_

2020-03-30

与父组件有关。props代表就是父子组件传值的属性。跟super(props)没关系。

子组件通过props获取父组件传来的值。

this.props.count是获取的父组件传递过来的count,然后赋值给了count

1
heixin_慕码人9177259
h 好的,谢谢您的帮助
h020-03-31
共1条回复

0 学习 · 10739 问题

查看课程