父组件向子组件传值
父组件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Parent extends Component {
state = {
count: 1
}
increment = () => {
let { count } = this.state
this.setState({count: ++count})
}
render() {
return(
<>
<button onClick={this.increment}>increment</button>
<Child count={this.state.count}/>
</>
)
}
}在子组件中通过
props
获取父组件传递的数据1
2
3
4
5
6
7class Child extends Component {
render() {
return(
<p>count: {this.props.count}</p>
)
}
}
子组件向父组件传值
父组件要获取子组件传递过来的值,可以在父组件中传递给子组件一个方法,子组件中通过这个方法传递传递参数,那么在父组件中通过调用这个方法即可取到这个值
- 父组件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class Parent extends Component {
state = {
count: 1
}
increment = () => {
let { count } = this.state
this.setState({ ++count })
}
toZero = count => {
this.setState({ count })
}
render() {
return(
<>
<button onClick={this.increment}>increment</button>
<Child count={this.state.count} toZero={this.toZero}/>
</>
)
}
}
- 子组件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15class Child extends Component {
toZero = () => {
this.props.toZero(0)
}
render() {
return(
<>
<p>count: {this.props.count}</p>
<button onClick={this.toZero}>toZero</button>
</>
)
}
}