react父组件调用子组件的方法 父子组件传值blog.csdn.net
注意点写在上边比较醒目
- 方法必须写成箭头函数,不然this的指向会出问题。
(不用箭头函数的话要用this.fn.bind(this)修正this的指向) - 父组件向子组件传值/方法比较简单,都是在属性中传然后在子组件中props获取。
- 子组件向父组件传值是通过事件进行传值。
父组件向子组件传值
//父组件中
import React, { Component } from "react";
import Child from "./Child";
class Dad extends Component {
constructor(props) {
super(props);
this.state = {
arr:["暴富","暴瘦"],
}
}
render() {
return (
<div>
//写在子组件的属性中
<Child arr={this.state.arr}></Child>
</div>
)
}
}
export default Dad;
//子组件中
import React, { Component } from "react";
class Child extends Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<ul>
{
//再用props获取
this.props.arr.map(el=>{
return (
<li key={el}>{el}</li>
)
})
}
</ul>
</div>
)
}
}
export default Child;
在子组件中调用父组件中的方法
//父组件
import React, { Component } from "react";
import Child from "./Child";
class Dad extends Component {
constructor(props) {
super(props);
}
dadFn=()=>{
console.log("我是父组件中的方法")
}
render() {
return (
<div>
<Child dadFn={this.dadFn}></Child>
</div>
)
}
}
export default Dad;
//子组件
import React, { Component } from "react";
class Child extends Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<button onClick={this.props.dadFn}>在子组件中调用父组件中的方法</button>
</div>
)
}
}
export default Child;
子组件向父组件传值
//父组件
import React, { Component } from "react";
import Child from "./Child";
class Dad extends Component {
constructor(props) {
super(props);
this.state = {
txt:"我是尼爸爸"
}
}
fn=(data)=>{
this.setState({
txt:data
})
}
render() {
return (
<div>
<Child cfn={this.fn}></Child>
<p>{this.state.txt}</p>
</div>
)
}
}
export default Dad;
//子组件
import React, { Component } from "react";
class Child extends Component {
constructor(props){
super(props);
}
fn=(data)=>{
this.props.cfn(data);
}
render() {
return (
<div>
//通过事件进行传值
<button onClick={()=>{this.fn("我是儿子")}}>子组件向父组件传值</button>
</div>
)
}
}
export default Child;
父组件调用子组件中的方法
//父组件
import React, { Component } from "react";
import Child from "./Child";
class Dad extends Component {
constructor(props) {
super(props);
this.state = {
arr:["暴富","暴瘦"],
txt:"我是尼爸爸"
}
}
onRef=(ref)=>{
this.Child=ref;
}
click=()=>{
this.Child.childFn();
}
render() {
return (
<div>
<Child onRef={this.onRef}></Child>
<button onClick={this.click}>父组件调用子组件中的方法</button>
</div>
)
}
}
export default Dad;
//子组件
import React, { Component } from "react";
class Child extends Component {
constructor(props){
super(props);
}
componentDidMount() {
this.props.onRef(this)
}
childFn=()=>{
console.log("我是子组件中的方法")
}
render() {
return (
<div>
</div>
)
}
}
export default Child;