react中的子组件向父组件传值,是先通过在父组件中将一个更新视图的方法传给子组件,然后子组件通过这个方法向这个方法传递参数,从而达到父组件的视图更新(数据的重新赋值)的效果。
1、父组件
具体测试代码:
父组件
import React, {Component} from "react";
import Children from "./components/Children"
class App extends Component {
state = {
name:'小陈同学',
msgData:1000
}
handleChange = (res) => {
console.log('打印父组件中的数据:',this.state);
// res作为形参
this.setState({
name:res
})
}
render() {
console.log('打印父组件中的数据:',this.state);
return (
<>
<h5>{this.state.name}</h5>
<Children sendFn={this.handleChange}/>
</>
)
}
}
export default App;
子组件
import React,{Component} from "react";
export default class Children extends Component {
state = {
newName:'张三'
}
handleClick = () => {
const { newName } = this.state;
const { sendFn } = this.props;
sendFn(newName)
}
render(){
return (
<>
<button onClick={this.handleClick}>点击传递数据</button>
</>
)
}
}