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 (
//写在子组件的属性中
)
}
}
export default Dad;
//子组件中
import React, { Component } from "react";
class Child extends Component {
constructor(props){
super(props);
}
render() {
return (
{
//再用props获取
this.props.arr.map(el=>{
return (
{el})
})
}
)
}
}
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 (
)
}
}
export default Dad;
//子组件
import React, { Component } from "react";
class Child extends Component {
constructor(props){
super(props);
}
render() {
return (
在子组件中调用父组件中的方法
)
}
}
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 (
{this.state.txt}
)
}
}
export default Dad;
//子组件
import React, { Component } from "react";
class Child extends Component {
constructor(props){
super(props);
}
fn=(data)=>{
this.props.cfn(data);
}
render() {
return (
//通过事件进行传值
{this.fn("我是儿子")}}>子组件向父组件传值
)
}
}
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 (
父组件调用子组件中的方法
)
}
}
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 (
)
}
}
export default Child;