如何从React.js中的另一个类组件调用方法



所以我必须对组件进行分类:
Class1:有一个点击按钮
Class2:有一个方法调用我的api

基本上,我想要的是调用一个方法,从另一个类中设置和编辑一个类内部的状态。但我一直在失败。

示例:

Class1.js
export class Class1 extends Component {
render() {
return (
<div onClick={must call Class2Method}></div>
)
}
}
Class2.js
export class Class2 extends Component {
Class2Method(){
Here I call my API, I set & call states, ...
}
render {
return (
<Class1 />
Here I return my API content
)    
}   
}

我尝试过的:

  1. 我试着在App.js(class2和class1的父级(中使用我的方法、调用和设置我的状态;但是我的Class2.js控制台说它找不到我的状态
  2. 我还尝试过:<Class1方法={this.Class2Method}/>,并且<div onClick={this.props.method}>

开始

Class1.js

export class Class1 extends Component {
render() {
return (
<div onClick={this.props.callApi}></div>
)
}
}

Class2.js

  1. 在构造函数中绑定callApi函数或将其更改为箭头函数
  2. 将callApi方法作为道具传递给class1组件,并在上面的组件中以this.props.callApi的形式访问它,然后将其传递给div.的onClick

    export class Class2 extends Component {
    callApi = () => {
    Here I call my API, I set & call states, ...
    }
    render {
    return (
    <Class1 callApi={this.callApi} />
    Here I return my API content
    )    
    }   
    }
    

如何从react.js 中的另一个类组件调用方法

使用道具

"render prop"指的是一种在React组件之间共享代码的技术,使用的是一个值为函数的prop

示例

app.js

import Button from '../../pathtoButton';
export class App extents Component {
constructor(props){
super(props)
this.state = {
name:'John'
}
}
sayHello(){
const { name } = this.message;
alert(`Hello ${name}`}
}
render(){
return (
<div>
<Button
value="click me"
whenClicked={this.sayHello}
</div>
);
}
}

按钮.js

export class Button extents Component {
constructor(props){
super(props)
this.state = {
style:{background:'red', color:'white'},
}
}
render(){
const { style } = this.state;
const { whenClicked, value} = this.props;
return (
<div>
<button style={style} onClick={whenClicked}>{value}</button>
</div>
);
}
}

解释

app.js中,我们导入了组件<Button/>,并使用props将方法从app.js"sayHello"传递给我们创建的名为whenClicked的道具。在button.js中,我们引用了this.props.whenClicked并将其传递给onClick属性。

sayHello现在在两个组件之间共享,因为我们将该方法作为道具传递给了<Button/>组件。

首先:在像"Class1"这样不使用状态、只使用道具的情况下,考虑使用无状态功能组件而不是有状态组件。

现在,做你需要的事。。只需将你的方法作为道具传递,就像这样:

export class Class1 extends Component {
render() {
return (
<div onClick={this.props.getData()}>Click to Call API</div>
);
}
}
export class Class2 extends Component {
state = {
data: null,
};

callApi = () => {
// Get API data
const data = {
hello: 'world',
};

this.setState({ data });
}

render {
return (
<Class1 getData={this.callApi} />
{JSON.stringify(this.state.data)}
)    
}   
}

最新更新